我试图在不影响特殊字符的情况下反转字符串,但没有成功。下面是我的代码:
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
7条答案
按热度按时间k2arahey1#
请尝试以下代码:
希望这能起作用...
svujldwt2#
或者用
itertools.groupby
试试这个,cwtwac6a3#
你是说像这样吗?:
mxg2im7a4#
uinbv5nw5#
下面是PHP中的解决方案。
c8ib6hqw6#
cczfrluj7#
def反向字符串(t):c=[] t=列表(t),i在t中:如果i是alpha():c.对于范围(len(t))中的i,append(i)反向字符串= c[::-1]计数= 0:如果不是t[i]. is alpha():reverse_string.insert(i,t[i])返回反向字符串打印(反向字符串(“a@bc%d”))