我对标题中所说的有疑问。基本上给我的句子包含地址-我只反转句子中的地址并返回字符串。我可以正确地反转地址,但是在返回整个字符串时遇到麻烦。我的代码:
def problem3(searchstring):
"""
Garble Street name.
:param searchstring: string
:return: string
"""
flag = 0
street = ""
#each word is considered in loop
for i in searchstring.split():
if i.endswith('.'): #if the word ends with .
flag = 0
stype = i
if flag == 1: #if the flag is 1
street = street + " " + i[::-1]
if i.isdigit(): #if the word is digit
flag =1
num = i
address = num + " " + street + " " + stype
return address
pass
使用以下函数调用:
print(problem3('The EE building is at 465 Northwestern Ave.'))
print(problem3('Meet me at 201 South First St. at noon'))
我的结果:
465 nretsewhtroN Ave.
201 htuoS tsriF St.
但是我想要的是:
The EE building is at 465 nretsewhtroN Ave.
Meet me at 201 tsriF htuoS St. at noon
我该如何解决?
尝试此
def problem3(searchstring):
"""
Garble Street name.
:param searchstring: string
:return: string
"""
flag = 0
street = ""
stri=""
#each word is considered in loop
for i in searchstring.split():
if i.endswith('.'): #if the word ends with .
flag = 0
stype = i
continue
if flag == 1: #if the flag is 1
street = street + " " + i[::-1]
continue
if i.isdigit(): #if the word is digit
flag =1
num = i
continue
stri=stri+' '+i
address =stri+" "+ num + " " + street + " " + stype
return address
然后,如果您调用该函数:
print(problem3('The EE building is at 465 Northwestern Ave.'))
print(problem3('Meet me at 201 South First St. at noon'))
输出将是
The EE building is at 465 nretsewhtroN Ave.
Meet me at at noon 201 htuoS tsriF St.