怎样组合数字python_如何将列表中的一部分数字组合在一起Python

我目前正在开发一个程序,在这个程序中,我必须将一个字符串作为输入,然后反转该字符串中的所有数字,保留所有其他字符不变。我成功地做到了这一点,但似乎我必须一次反转部分数字,而不是反转每个数字。我不知道如何用我的解决方案做到这一点。我宁愿不使用任何图书馆。在

例如: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)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值