我目前正在开发一个程序,在这个程序中,我必须将一个字符串作为输入,然后反转该字符串中的所有数字,保留所有其他字符不变。我成功地做到了这一点,但似乎我必须一次反转部分数字,而不是反转每个数字。我不知道如何用我的解决方案做到这一点。我宁愿不使用任何图书馆。在
例如:For input abc123abc456abc7891
My result: abc198abc765abc4321
Target Result: abc321abc654abc1987
以下是我所拥有的:#Fucntion just reverses the numbers that getn gives to it
def reverse(t):
t = t[::-1]
return t
def getn(w):
w = list(w)
Li = []
#Going through each character of w(the inputted string) and adding any numbers to the list Li
for i in w:
if i.isdigit():
Li.append(i)
#Turn Li back into a string so I can then reverse it using the above function
#after reversing, I turn it back into a list
Li = ''.join(Li)
Li = reverse(Li)
Li = list(Li)
#I use t only for the purpose of the for loop below,
#to get the len of the string,
#a is used to increment the position in Li
t = ''.join(w)
a = 0
#This goes through each position of the string again,
#and replaces each of the original numbers with the reversed sequence
for i in range(0,len(t)):
if w[i].isdigit():
w[i] = Li[a]
a+=1
#Turn w back into a string to print
w = ''.join(w)
print('New String:\n'+w)
x = input('Enter String:\n')
getn(x)