问题:在Python中更改字符串中的一个字符

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

例如:

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

What is the easiest way in Python to replace a character in a string?

For example:

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

回答 0

不要修改字符串。

与他们一起工作;仅在需要时才将它们转换为字符串。

>>> s = list("Hello zorld")
>>> s
['H', 'e', 'l', 'l', 'o', ' ', 'z', 'o', 'r', 'l', 'd']
>>> s[6] = 'W'
>>> s
['H', 'e', 'l', 'l', 'o', ' ', 'W', 'o', 'r', 'l', 'd']
>>> "".join(s)
'Hello World'

Python字符串是不可变的(即无法修改)。有很多的原因。除非您别无选择,否则请使用列表,然后将它们变成字符串。

Don’t modify strings.

Work with them as lists; turn them into strings only when needed.

>>> s = list("Hello zorld")
>>> s
['H', 'e', 'l', 'l', 'o', ' ', 'z', 'o', 'r', 'l', 'd']
>>> s[6] = 'W'
>>> s
['H', 'e', 'l', 'l', 'o', ' ', 'W', 'o', 'r', 'l', 'd']
>>> "".join(s)
'Hello World'

Python strings are immutable (i.e. they can’t be modified). There are a lot of reasons for this. Use lists until you have no choice, only then turn them into strings.


回答 1

最快的方法?

有三种方法。对于速度寻求者,我建议使用“方法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

方法2(快速方法)

由这个答案给出

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

Fastest method?

There are three ways. For the speed seekers I recommend ‘Method 2’

Method 1

Given by this answer

text = 'abcdefg'
new = list(text)
new[6] = 'W'
''.join(new)

Which is pretty slow compared to ‘Method 2’

timeit.timeit("text = 'abcdefg'; s = list(text); s[6] = 'W'; ''.join(s)", number=1000000)
1.0411581993103027

Method 2 (FAST METHOD)

Given by this answer

text = 'abcdefg'
text = text[:1] + 'Z' + text[2:]

Which is much faster:

timeit.timeit("text = 'abcdefg'; text = text[:1] + 'Z' + text[2:]", number=1000000)
0.34651994705200195

Method 3:

Byte array:

timeit.timeit("text = 'abcdefg'; s = bytearray(text); s[1] = 'Z'; str(s)", number=1000000)
1.0387420654296875

回答 2

new = text[:1] + 'Z' + text[2:]
new = text[:1] + 'Z' + text[2:]

回答 3

Python字符串是不可变的,您可以通过复制来更改它们。
做您想做的最简单的方法可能是:

text = "Z" + text[1:]

text[1:]返回字符串text从位置1到结束,位置从0开始计数,从而“1”是第二个字符。

编辑:您可以对字符串的任何部分使用相同的字符串切片技术

text = text[:1] + "Z" + text[2:]

或者,如果该字母仅出现一次,则可以使用下面建议的搜索和替换技术

Python strings are immutable, you change them by making a copy.
The easiest way to do what you want is probably:

text = "Z" + text[1:]

The text[1:] returns the string in text from position 1 to the end, positions count from 0 so ‘1’ is the second character.

edit: You can use the same string slicing technique for any part of the string

text = text[:1] + "Z" + text[2:]

Or if the letter only appears once you can use the search and replace technique suggested below


回答 4

从python 2.6和python 3开始,您可以使用可变的字节数组(可以与字符串不同,可以逐个元素地更改):

s = "abcdefg"
b_s = bytearray(s)
b_s[1] = "Z"
s = str(b_s)
print s
aZcdefg

编辑:更改为s

edit2:正如两位炼金术士在评论中所述,此代码不适用于unicode。

Starting with python 2.6 and python 3 you can use bytearrays which are mutable (can be changed element-wise unlike strings):

s = "abcdefg"
b_s = bytearray(s)
b_s[1] = "Z"
s = str(b_s)
print s
aZcdefg

edit: Changed str to s

edit2: As Two-Bit Alchemist mentioned in the comments, this code does not work with unicode.


回答 5

就像其他人所说的那样,通常Python字符串应该是不可变的。

但是,如果您使用的是CPython,即python.org的实现,则可以使用ctypes修改内存中的字符串结构。

这是我使用该技术清除字符串的示例。

在python中将数据标记为敏感

为了完整起见,我提到了这一点,这应该是您的最后选择,因为它有点黑。

Like other people have said, generally Python strings are supposed to be immutable.

However, if you are using CPython, the implementation at python.org, it is possible to use ctypes to modify the string structure in memory.

Here is an example where I use the technique to clear a string.

Mark data as sensitive in python

I mention this for the sake of completeness, and this should be your last resort as it is hackish.


回答 6

此代码不是我的。我不记得我在哪里填写网站表格。有趣的是,您可以使用此字符用一个或多个字符替换一个或多个字符。尽管此回复很晚,但像我这样的新手(随时)可能会觉得有用。

更改文字功能。

mytext = 'Hello Zorld'
mytext = mytext.replace('Z', 'W')
print mytext,

This code is not mine. I couldn’t recall the site form where, I took it. Interestingly, you can use this to replace one character or more with one or more charectors. Though this reply is very late, novices like me (anytime) might find it useful.

Change Text function.

mytext = 'Hello Zorld'
mytext = mytext.replace('Z', 'W')
print mytext,

回答 7

实际上,使用字符串,您可以执行以下操作:

oldStr = 'Hello World!'    
newStr = ''

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

'HELLO WORLD!'

基本上,我是将“ +”字符串一起添加到新字符串中:)。

Actually, with strings, you can do something like this:

oldStr = 'Hello World!'    
newStr = ''

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

'HELLO WORLD!'

Basically, I’m “adding”+”strings” together into a new string :).


回答 8

如果您的世界是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

if your world is 100% ascii/utf-8(a lot of use cases fit in that box):

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

python 3.7.3


回答 9

我想添加另一种更改字符串中字符的方式。

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

与将字符串转换为list并替换ith值然后再次加入相比,速度有多快?

清单方式

>>> 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

I would like to add another way of changing a character in a string.

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

How faster it is when compared to turning the string into list and replacing the ith value then joining again?.

List approach

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

My solution

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

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。