[英]replace (not remove) a character with condition
How do I use the replace
function to replace all instances with the exception of one.如何使用
replace
function 替换除一个之外的所有实例。
mystr = "he said: 'hi my name's Jim'."
mystr.replace("'", '"')
print(mystr)
The output I would want is: he said: "hi my name's Jim".
我想要的 output 是:
he said: "hi my name's Jim".
How do I exclude 's
from the replace?如何从替换中排除
's
? ie exclude all '
followed by an s
and where the '
is preceded by digit/letter.即排除所有
'
后跟一个s
并且'
前面是数字/字母。
if mystr2 = "'s: hi'"
then I wouldn't want to replace the first '
only replace the second '
.如果
mystr2 = "'s: hi'"
那么我不想替换第一个'
只替换第二个'
。
UPDATE Removing single quotes if they aren't in the middle of a word This shows how to remove the required quotes, but not how to replace it.更新如果单引号不在单词的中间,则删除它们这显示了如何删除所需的引号,而不是如何替换它。
Better approach would be to use this regex:更好的方法是使用这个正则表达式:
\B'\b|\b'\B
and replace with "
.并替换为
"
。
\b
: Word boundary \b
:单词边界\B
: inverse of \b
or word boundary \B
: \b
或单词边界的倒数>>> import re
>>> mystr = "he said: 'hi my name's Jim'."
>>> print (re.sub(r"\B'\b|\b'\B", '"', mystr))
he said: "hi my name's Jim".
another regex: '(?!s)
replaces every '
that is not followed by a s
另一个正则表达式:
'(?!s)
替换每个'
后面没有s
import re
mystr = "he said: 'hi my name's Jim'."
newstr = re.sub(r"'(?!s)", '"', mystr)
print(newstr)
output: he said: "hi my name's Jim".
output:
he said: "hi my name's Jim".
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.