在Python中替换字符串中的字符最简单的方法是什么?

例如:

text = "abcdefg";
text[1] = "Z";
           ^

当前回答

实际上,对于字符串,你可以这样做:

oldStr = 'Hello World!'    
newStr = ''

for i in oldStr:  
    if 'a' < i < 'z':    
        newStr += chr(ord(i)-32)     
    else:      
        newStr += i
print(newStr)

'HELLO WORLD!'

基本上,我是“添加”+“字符串”一起成为一个新的字符串:)。

其他回答

实际上,对于字符串,你可以这样做:

oldStr = 'Hello World!'    
newStr = ''

for i in oldStr:  
    if 'a' < i < 'z':    
        newStr += chr(ord(i)-32)     
    else:      
        newStr += i
print(newStr)

'HELLO WORLD!'

基本上,我是“添加”+“字符串”一起成为一个新的字符串:)。

如果你的世界是100% ascii/utf-8(很多用例适合这个盒子):

b = bytearray(s, 'utf-8')
# process - e.g., lowercasing: 
#    b[0] = b[i+1] - 32
s = str(b, 'utf-8')

python 3.7.3

最快的方法?

有三种方法。对于追求速度的人,我推荐“方法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

替换字符串中的一个字符

你可以使用以下任何一种方法:

方法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:]

我想添加另一种改变字符串中的字符的方法。

>>> text = '~~~~~~~~~~~'
>>> text = text[:1] + (text[1:].replace(text[0], '+', 1))
'~+~~~~~~~~~'

与将字符串转换为列表并替换第i个值然后再次连接相比,它有多快?

列表的方法

>>> timeit.timeit("text = '~~~~~~~~~~~'; s = list(text); s[1] = '+'; ''.join(s)", number=1000000)
0.8268570480013295

我的解决方案

>>> timeit.timeit("text = '~~~~~~~~~~~'; text=text[:1] + (text[1:].replace(text[0], '+', 1))", number=1000000)
0.588400217000526