在Python中替换字符串中的字符最简单的方法是什么?
例如:
text = "abcdefg";
text[1] = "Z";
^
在Python中替换字符串中的字符最简单的方法是什么?
例如:
text = "abcdefg";
text[1] = "Z";
^
Python字符串是不可变的,你可以通过复制来改变它们。 做你想做的事情最简单的方法可能是:
text = "Z" + text[1:]
文本[1:]返回文本中从位置1到末尾的字符串,位置从0开始计数,因此'1'是第二个字符。
编辑: 您可以对字符串的任何部分使用相同的字符串切片技术
text = text[:1] + "Z" + text[2:]
或者如果字母只出现一次,你可以使用搜索和替换技巧 下面
不要修改字符串。
将它们作为列表来处理;只在需要时将它们转换为字符串。
>>> 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字符串是不可变的(即它们不能被修改)。这有很多原因。使用列表,直到你别无选择,然后才把它们变成字符串。
正如其他人所说,通常Python字符串应该是不可变的。
但是,如果你使用的是CPython (python.org上的实现),则可以使用ctypes来修改内存中的字符串结构。
下面是我使用该技术清除字符串的示例。
在python中将数据标记为敏感
为了完整起见,我提到了这一点,这应该是您最后的手段,因为它很粗糙。
这个代码不是我的。我不记得是在哪里拍的。有趣的是,您可以使用它来用一个或多个字符替换一个或多个字符。 虽然这个回复很晚,但像我这样的新手(任何时候)可能会发现它很有用。
更改文本功能。
mytext = 'Hello Zorld'
# change all Z(s) to "W"
while "Z" in mytext:
# replace "Z" to "W"
mytext = mytext.replace('Z', 'W')
print(mytext)
从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。
最快的方法?
有三种方法。对于追求速度的人,我推荐“方法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
实际上,对于字符串,你可以这样做:
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
我想添加另一种改变字符串中的字符的方法。
>>> 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
字符串在Python中是不可变的,这意味着你不能改变现有的字符串。 但如果你想改变其中的任何字符,你可以创建一个新的字符串,如下所示,
def replace(s, position, character):
return s[:position] + character + s[position+1:]
replace('King', 1, 'o') // result: Kong
注意:如果你给出的位置值大于字符串的长度,它将在结尾追加字符。
replace('Dog', 10, 's') //结果:狗
在单行if语句中结合find和replace方法的解决方案可以是:
```python
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
```
试试这个:
old_string = "mba"
string_list = list(old_string)
string_list[2] = "e"
//Replace 3rd element
new_string = "".join(string_list)
print(new_string)
我喜欢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:]