【发布时间】:2020-06-19 00:58:48
【问题描述】:
我对标题中所说的内容有疑问。基本上我得到包含地址的句子 - 我只反转句子中的地址并返回字符串。我可以很好地反转地址,但在返回整个字符串时遇到了麻烦。我的代码:(编辑:现已更正):
def problem3(searchstring):
"""
Garble Street name.
:param searchstring: string
:return: string
"""
flag = 0
output = ""
#each word is considered in loop
for i in searchstring.split():
if i.endswith('.'): #if the word ends with .
flag = 0
stype = i
output += " " + stype
elif flag == 1: #if the flag is 1
#street =
output += " " + i[::-1]
elif i.isdigit(): #if the word is digit
flag =1
#num = i
output += i
else:
output += i + " "
#address = num + " " + street + " " + stype
return output
【问题讨论】:
-
您可能需要为此使用正则表达式,例如 this one,
re.sub(r'(\d+\s+)(.*?)(\s+\S+\.)(?!\S)', lambda x: f"{x.group(1)}{x.group(2)[::-1]}{x.group(3)}", text)
标签: python string text-processing text-parsing