我试图在不影响特殊字符的情况下反转一个字符串,但它不工作。这是我的代码。
def reverse_each_word(str_smpl):
str_smpl = "String; 2be reversed..." #Input that want to reversed
lst = []
for word in str_smpl.split(' '):
letters = [c for c in word if c.isalpha()]
for c in word:
if c.isalpha():`enter code here`
lst.append(letters.pop())
continue
else:
lst.append(c)
lst.append(' ')
print("".join(lst))
return str_smpl
def main(): #This is called for assertion of output
str_smpl = "String; 2be reversed..." #Samplr input
assert reverse_each_word(str_smpl) == "gnirtS; eb2 desrever..." #output should be like this
return 0
试试下面的代码。
from string import punctuation
sp = set(punctuation)
str_smpl = "String; 2be reversed..." #Input that want to reversed
lst = []
for word in str_smpl.split(' '):
letters = [c for c in word if c not in sp]
for c in word:
if c not in sp:
lst.append(letters.pop())
continue
else:
lst.append(c)
lst.append(' ')
print("".join(lst))
希望这能奏效...
或者试试这个 itertools.groupby
,
import itertools
def reverse_special_substrings(s):
ret = ''
for isalnum, letters in itertools.groupby(s, str.isalnum):
letters = list(letters)
if isalnum:
letters = letters[::-1]
ret += ''.join(letters)
return ret
你是说像这样吗?
def reverse_string(st):
rev_word=''
reverse_str=''
for l in st:
if l.isalpha():
rev_word=l+rev_word
else:
reverse_str+=rev_word
rev_word=''
reverse_str+=l
return reverse_str
def main():
string=' Hello, are you fine....'
print(reverse_string(string))
if __name__=='__main__':
main()