更改字符串中的字符
- 2024-12-03 08:44:00
- admin 原创
- 149
问题描述:
在 Python 中替换字符串中字符的最简单方法是什么?
例如:
text = "abcdefg";
text[1] = "Z";
^
解决方案 1:
不要修改字符串。
将它们作为列表使用;仅在需要时将它们转换为字符串。
>>> 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 字符串是不可变的(即它们不能被修改)。这有很多原因。除非别无选择,否则请使用列表,然后才将它们转换为字符串。
解决方案 2:
最快的方法?
有三种方法。
对于追求速度的人,我推荐“方法 2”
方法 1:
由scvalex 的答案给出:
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(快速方法):
Jochen Ritzel 的回答给出:
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
解决方案 3:
new = text[:1] + 'Z' + text[2:]
解决方案 4:
Python 字符串是不可变的,您可以通过复制来更改它们。
最简单的方法可能是:
text = "Z" + text[1:]
返回从位置 1 到末尾text[1:]
的字符串,位置从 0 开始计数,因此“1”是第二个字符。text
编辑:你可以对字符串的任何部分使用相同的字符串切片技术
text = text[:1] + "Z" + text[2:]
或者如果该字母只出现一次,您可以使用下面建议的搜索和替换技术
解决方案 5:
从 python 2.6 和 python 3 开始,您可以使用可变的字节数组(与字符串不同,可以逐个元素地更改):
s = "abcdefg"
b_s = bytearray(s)
b_s[1] = "Z"
s = str(b_s)
print s
aZcdefg
编辑:将 str 更改为 s
编辑2:正如 Two-Bit Alchemist 在评论中提到的,该代码不适用于 unicode。
解决方案 6:
在 Python 中,字符串是不可变的,这意味着你不能更改现有的字符串。但是如果你想要更改其中的任何字符,你可以创建一个新的字符串,如下所示,
def replace(s, position, character):
return s[:position] + character + s[position+1:]
replace('King', 1, 'o')
// 结果:Kong
注意:如果您给出的位置值大于字符串的长度,它会将字符附加到末尾。
replace('Dog', 10, 's')
// 结果:Dogs
解决方案 7:
正如其他人所说的那样,Python 字符串通常被认为是不可变的。
但是,如果您使用 CPython(python.org 上的实现),则可以使用 ctypes 修改内存中的字符串结构。
下面是我使用该技术清除字符串的一个例子。
在python中将数据标记为敏感数据
我提到这一点是为了完整性,而且这应该是你的最后手段,因为它很黑客。
解决方案 8:
此代码不是我的。我不记得我把它从哪个网站下载了。有趣的是,你可以用它将一个或多个字符替换为一个或多个字符。虽然这个回复很晚,但像我这样的新手(任何时候)可能会发现它很有用。
更改文本功能。
mytext = 'Hello Zorld'
# change all Z(s) to "W"
while "Z" in mytext:
# replace "Z" to "W"
mytext = mytext.replace('Z', 'W')
print(mytext)
解决方案 9:
我喜欢 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
>>>
解决方案 10:
实际上,使用字符串,你可以做这样的事情:
oldStr = 'Hello World!'
newStr = ''
for i in oldStr:
if 'a' < i < 'z':
newStr += chr(ord(i)-32)
else:
newStr += i
print(newStr)
'HELLO WORLD!'
基本上,我将“添加”+“字符串”一起添加到一个新字符串中:)。
解决方案 11:
如果您只更改一个字符,那么Jochen Ritzel 使用字符串切片的答案是最快的(在我看来也是最易读的)。但是,如果您要按位置更改字符串中的多个字符,则这种方式的扩展性不佳。在这种情况下,有一个内置array
模块可能有助于转换字符串可变对象并更改所需的字符。显然,转换为列表(如在接受的答案中所做的那样)也可以,但它非常慢。
import array
text = "HXlYo wZrWd"
ix = [1, 3, 7, 9]
vs = ['e', 'l', 'o', 'l']
ar = array.array('u', text) # convert `text` string to array.array object
for i,v in zip(ix, vs):
ar[i] = v # change characters by index
out = ar.tounicode() # convert back to string
print(out) # Hello world
解决方案 12:
如果你的世界是 100% ascii/utf-8
(很多用例都适合这个框):
b = bytearray(s, 'utf-8')
# process - e.g., lowercasing:
# b[0] = b[i+1] - 32
s = str(b, 'utf-8')
蟒蛇3.7.3
解决方案 13:
替换字符串中的字符
您可以使用以下任一方法:
方法 1
一般来说,
string = f'{string[:index]}{replacing_character}{string[index+1:]}'
这里
text = f'{text[:1]}Z{text[2:]}'
方法 2
一般来说,
string = string[:index] + replacing_character + string[index+1:]
这里,
text = text[:1] + 'Z' + text[2:]
解决方案 14:
在一行 if 语句中结合查找和替换方法的解决方案可以是:
my_var = "stackoverflaw"
my_new_var = my_var.replace('a', 'o', 1) if my_var.find('s') != -1 else my_var
print(f"my_var = {my_var}") # my_var = stackoverflaw
print(f"my_new_var = {my_new_var}") # my_new_var = stackoverflow
解决方案 15:
我想添加另一种改变字符串中字符的方法。
>>> 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
解决方案 16:
试试这个:
old_string = "mba"
string_list = list(old_string)
string_list[2] = "e"
//Replace 3rd element
new_string = "".join(string_list)
print(new_string)