如何在python中更改特定的字符串顺序

时间:2018-08-03 12:16:31

标签: python string python-2.7

使用Python 2.7运行Win 7。我想更改字符串:

  • ‘%01#WDD00300003010F123456’

收件人:

  • ‘%01#WDD0030000301120F5634’

因此,我想将最后8个字符从0F123456更改为120F5634。我该如何编写代码来实现这一目标?

6 个答案:

答案 0 :(得分:0)

如果您知道要替换多少个字符,列表切片将起作用。

从空闲状态开始:

>>> longstr = "this is a somewhat lengthy string"
>>> longstr[:5]
'this '
>>> longstr[5:]
'is a somewhat lengthy string'
>>> longstr[:-5]
'this is a somewhat lengthy s'
>>> longstr = longstr[:-6] + "road"
>>> longstr
'this is a somewhat lengthy road'

答案 1 :(得分:0)

尝试:

def shuffle(strVal):
    val = strVal[-8:]
    temp = [val[i:i+2] for i in range(0, len(val), 2)]
    res = "" 
    for i in zip(temp[::2], temp[1::2]):
        res = res + "".join([i[1], i[0]])

    return strVal[:-8] + res

s =  "%01#WDD00300003010F123456"
print shuffle(s)

输出:

%01#WDD0030000301120F5634

答案 2 :(得分:0)

使用re模块的另一尝试:

import re

s = """‘%01#WDD00300003010F123456’"""

print(re.sub(r'(.{2})(.{2})(.{2})(.{2})’', r'\2\1\4\3’', s))

打印:

‘%01#WDD0030000301120F5634’

答案 3 :(得分:0)

在要交换数字的位置切掉:

s = "%01#WDD00300003010F123456"
sb, se = s[:-8], s[-8:]

现在定义一个将se分成数字对的函数:

def digit_pairs(s):
    return [s[i:i+2] for i in range(0,len(s),2)]

和用于切换配对的功能:

def switch(s):
    for i in range(1,len(s),2):
        yield  s[i]
        yield  s[i-1]

那你就可以做

>>> ''.join(switch(digit_pairs(se)))
'120F5634'

答案 4 :(得分:-1)

尝试一下:替换将对您有用。

a="%01#WDD00300003010F123456"
a.replace("0F123456","120F5634")

答案 5 :(得分:-1)

我解决为打击:

str1 = '%01#WDD00300003010F123456'
ol
str2 = str1[:-8]

str3 = str2 + '120F5634'
print(str1)
print(str3)