在Python中替换字符串中的字符最简单的方法是什么?
例如:
text = "abcdefg";
text[1] = "Z";
^
在Python中替换字符串中的字符最简单的方法是什么?
例如:
text = "abcdefg";
text[1] = "Z";
^
当前回答
最快的方法?
有三种方法。对于追求速度的人,我推荐“方法2”
方法1
由这个答案给出
text = 'abcdefg'
new = list(text)
new[6] = 'W'
''.join(new)
这比方法2慢多了
timeit.timeit("text = 'abcdefg'; s = list(text); s[6] = 'W'; ''.join(s)", number=1000000)
1.0411581993103027
方法二(快速法)
由这个答案给出
text = 'abcdefg'
text = text[:1] + 'Z' + text[2:]
哪个更快:
timeit.timeit("text = 'abcdefg'; text = text[:1] + 'Z' + text[2:]", number=1000000)
0.34651994705200195
方法3:
字节数组:
timeit.timeit("text = 'abcdefg'; s = bytearray(text); s[1] = 'Z'; str(s)", number=1000000)
1.0387420654296875
其他回答
我喜欢f弦:
text = f'{text[:1]}Z{text[2:]}'
在我的机器中,这种方法比使用+来连接字符串的“快速方法”快10%:
>>> timeit.timeit("text = 'abcdefg'; text = text[:1] + 'Z' + text[2:]", number=1000000)
1.1691178000000093
>>> timeit.timeit("text = 'abcdefg'; text = f'{text[:1]}Z{text[2:]}'", number =1000000)
0.9047831999999971
>>>
替换字符串中的一个字符
你可以使用以下任何一种方法:
方法1
一般来说,
string = f'{string[:index]}{replacing_character}{string[index+1:]}'
Here
text = f'{text[:1]}Z{text[2:]}'
方法2
一般来说,
string = string[:index] + replacing_character + string[index+1:]
在这里,
text = text[:1] + 'Z' + text[2:]
从python 2.6和python 3开始,你可以使用可变的bytearrays(可以像字符串那样按元素改变):
s = "abcdefg"
b_s = bytearray(s)
b_s[1] = "Z"
s = str(b_s)
print s
aZcdefg
编辑:将str改为s
edit2:正如Two-Bit Alchemist在评论中提到的,这段代码不能使用unicode。
实际上,对于字符串,你可以这样做:
oldStr = 'Hello World!'
newStr = ''
for i in oldStr:
if 'a' < i < 'z':
newStr += chr(ord(i)-32)
else:
newStr += i
print(newStr)
'HELLO WORLD!'
基本上,我是“添加”+“字符串”一起成为一个新的字符串:)。
正如其他人所说,通常Python字符串应该是不可变的。
但是,如果你使用的是CPython (python.org上的实现),则可以使用ctypes来修改内存中的字符串结构。
下面是我使用该技术清除字符串的示例。
在python中将数据标记为敏感
为了完整起见,我提到了这一点,这应该是您最后的手段,因为它很粗糙。