这是我到目前为止编写的代码:
def first_word(text: str) -> str:
while text.find(' ') == 0:
text = text[1:]
while text.find('.') == 0:
text = text[1:]
while text.find(' ') == 0:
text = text[1:]
while text.find('.') == 0:
text = text[1:]
if text.find('.') != -1:
text = text.split('.')
elif text.find(',') != -1:
text = text.split(',')
elif text.find(' ') != -1:
text = text.split(' ')
text = text[0]
return text
它应该隔离字符串中的第一个单词,它会删除任何“。”,“”,“,”并仅保留单词本身。
答案 0 :(得分:2)
使用re
和split()
:
import re
ss = 'ba&*(*seball is fun'
print(''.join(re.findall(r'(\w+)', ss.split()[0])))
输出:
baseball
答案 1 :(得分:1)
sentence="bl.a, bla bla"
first_word=first_word.replace(".","").replace(",","")
first_word=sentence.split(" ")[0]
print(first_word)
或者您可以尝试列表理解:
sentence="bl.a, bla bla"
first_word=''.join([e for e in first_word if e not in ".,"]) #or any other punctuation
first_word=sentence.split(" ")[0]
print(first_word)