如何使用 rfind 返回以 ‘ing’ 结尾的单词?

huangapple go评论62阅读模式
英文:

How to return words ending with 'ing' using rfind?

问题

我想要返回所有以'ing'结尾的单词,使用rfind。

x = str(input("输入一些随机单词: "))

for y in x.split():
    if x.rfind(r'\b(\w+ing)\b'):
        print(y, end=' ') 

当我输入'How are you doing and hows it going'作为输入时,我得到整个字符串作为输出。我想要得到单词'doing'和'going'作为输出。

英文:

I am looking to return all the words ending in 'ing' using rfind.

x = str(input("Enter some random words: "))

for y in x.split():
    if x.rfind(r'\b(\w+ing)\b'):
        print(y, end=' ')

When I enter 'How are you doing and hows it going' as the input, I am getting the whole string as the output. I want to get the word 'doing' and 'going' as the output.

答案1

得分: 1

直接使用 str.endswith 在每个单词上:

for y in x.split():
    if y.endswith('ing'):
        print(y, end=' ')

如果要使用正则表达式,导入 re 模块并使用 re.findall

import re
print(*re.findall(r'\w+ing\b', x))
英文:

Directly use str.endswith on each word:

for y in x.split():
    if y.endswith('ing'):
        print(y, end=' ')

If you want to use regular expressions, import the re module and use re.findall:

import re
print(*re.findall(r'\w+ing\b', x))

huangapple
  • 本文由 发表于 2023年3月20日 23:21:37
  • 转载请务必保留本文链接:https://go.coder-hub.com/75792148.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定