我目前正在开发一个程序,在该程序中,我必须将一个字符串作为输入,然后反转该字符串中的所有数字,并使所有其他字符保持不变。我设法做到了这一点,但似乎我必须一次反转部分数字,而不是反转每个数字。我不确定如何使用我的解决方案来做到这一点。我不想使用任何库。
例如:
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)
请您参考如下方法:
解决方案概要:
- 将字符串分解为子字符串列表。每个子串由数字和非数字之间的划分定义。你在这个阶段结束时的结果应该是
["abc", "123", "abc", "456", "abc", "7891"] - 查看此列表;将每个数字字符串替换为它的反义词。
将此列表加入成一个字符串。
最后一步就是 ''.join(substring_list)。
中间步骤包含在您已经在做的事情中。
第一步并不简单,但在您原始帖子的编码能力范围内。
你能从这里拿走吗?
更新
这是根据需要将字符串分成组的逻辑。 检查每个字符的“数字性”。如果它与之前的字符不同,那么你必须开始一个新的子串。
instr = "abc123abc456abc7891"
substr = ""
sub_list = []
prev_digit = instr[0].isdigit()
for char in instr:
# if the character's digit-ness is different from the last one,
# then "tie off" the current substring and start a new one.
this_digit = char.isdigit()
if this_digit != prev_digit:
sub_list.append(substr)
substr = ""
prev_digit = this_digit
substr += char
# Add the last substr to the list
sub_list.append(substr)
print(sub_list)
输出:
['abc', '123', 'abc', '456', 'abc', '7891']
