[英]Python replace word with "word"
How can I replace word with "word" in python?如何在python中用“word”替换单词? I've already tried this:我已经试过了:
str = "some_word"
str.replace("some_word", '"some_word"')
but this doesn't work但这不起作用
1) Don't use str as variable name as it is keyword in python. 1)不要使用str作为变量名,因为它是python中的关键字。
d = 'ab'
print(d.replace('ab','ac'))
2) String are immutable in python so you have to re-assign it like: 2)字符串在python中是不可变的,所以你必须像这样重新分配它:
d = d.replace('ab','ac')
print(d)
This perfectly works:这完全有效:
a = "some_word"
print(a) # some_word
a = a.replace("some_word", '"some_word"')
print(a) # "some_word"
If you want to wrap the entire string in double quotes, and not only a part of it, you may use one of these approaches:如果您想用双引号将整个字符串括起来,而不仅仅是其中的一部分,您可以使用以下方法之一:
a = "some_word"
a1 = '"{}"'.format(a)
a2 = '"' + a + '"'
a3 = f'"{a}"'
you should create a variable to receive the replaced value.您应该创建一个变量来接收替换的值。
str = "some_word"
str = replace(old_chars, new_chars)
>>> strr = "some_word"
>>> strr = f'"{strr}"'
>>> print(strr)
"some_word"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.