输入:"We are Testing."
输出:['We', 'Testing']
输入:"Hello1 Hello2 Hello3"
输出:['Hello1', 'Hello2', 'Hello3']
如果字符串中没有这样的词,则返回'None'
有没有一种有效的方法来解决这个问题,我尝试拆分字符串,但似乎效果不佳。
答案 0 :(得分:1)
函数以字符串为参数进行处理
def finder(string):
words_list = string.split(' ')
# Check if the first letter is uppercase and is alphanumerical
# Else remove the word from list
words_list = [i for i in words_list if i == i.capitalize() and i.isalnum()]
return words_list
答案 1 :(得分:0)
您可以通过列表理解来实现这一点。
def find(string):
... s = [s for s in string.split(" ") if s[0].isupper()]
... return s or None
...
>>> print(find("no one is here"))
None
>>> print(find("Hello world"))
['Hello']
>>> print(find("We are Testing."))
['We', 'Testing.']
>>> print(find("Hello1 Hello2 Hello3"))
['Hello1', 'Hello2', 'Hello3']