在Python中反转一个字符串,但保持原始顺序的数字

时间:2017-11-11 07:56:56

标签: python string

我可以使用[::- 1]语法反转字符串。请注意以下示例:

text_in = 'I am 25 years old'
rev_text = text_in[::-1]
print rev_text

输出:

dlo sraey 52 ma I

如何在保持数字顺序的同时只反转字母?

示例的期望结果是'dlo sraey 25 ma I'

5 个答案:

答案 0 :(得分:8)

这是dplyr的方法:

re

答案 1 :(得分:6)

使用split()join()以及str.isdigit()来识别数字:

>>> s = 'I am 25 years old'
>>> s1 = s.split()
>>> ' '.join([ ele if ele.isdigit() else ele[::-1] for ele in s1[::-1] ])
=> 'dlo sraey 25 ma I'

注意:这仅适用于空格分隔的数字。对于其他人,请使用regex查看timegeb's回答。

答案 2 :(得分:2)

这是一步一步的方法:

text_in = 'I am 25 years old'
text_seq = list(text_in)                          # make a list of characters
text_nums = [c for c in text_seq if c.isdigit()]  # extract the numbers

num_ndx = 0
revers = []
for idx, c in enumerate(text_seq[::-1]):          # for each char in the reversed text
    if c.isdigit():                               # if it is a number
        c = text_nums[num_ndx]                    # replace it by the number not reversed
        num_ndx += 1
    revers.append(c)                              # if not a number, preserve the reversed order
print(''.join(revers))                            # output the final string              

输出:

dlo sraey 25 ma I

答案 3 :(得分:1)

您可以像 pythonic 那样直接进行,如下所示..

def rev_except_digit(text_in):
    rlist = text_in[::-1].split() #Reverse the whole string and split into list

    for i in range(len(rlist)): # Again reverse only numbers
        if rlist[i].isdigit():
            rlist[i] = rlist[i][::-1]
    return ' '.join(rlist)

测试:

Original: I am 25 years 345 old 290
Reverse: 290 dlo 345 sraey 25 ma I

你可以在这里找到官方python doc split() and other string methodsslicing[::-1]

答案 4 :(得分:-1)

text = "I am 25 years old"
new_text = ''
text_rev = text[::-1]
for i in text_rev.split():
    if not i.isdigit():
         new_text += i + " ";
    else:
        new_text += i[::-1] + " ";


print(new_text)