我有一个字符串srting=123d*gss6agn
我如何删除=
之后的所有内容并留空
我应该使用re还是string模块,我该怎么解决
答案 0 :(得分:4)
尝试一下:
a="srting=123d*gss6agn"
a.split("=")[0]+"="
或者这个:
a="srting=123d*gss6agn"
a[:a.index("=")+1]
要打开文件:
with open("path/to/your/file.txt","r") as f:
a=f.read() # and then use an option above
答案 1 :(得分:2)
如果您想使用正则表达式...尽管我个人会选择其他答案。
import re
a = "srting=123d*gss6agn"
result = re.sub(r'=.','=',a)
用等号替换等号后的所有文本。
答案 2 :(得分:1)
使用partition():
s='srting=123d*gss6agn'
s,separator,remainder=s.partition("=")
print(s)
Out:
'srting'
(如果缺少'=',也不例外。)
只需播放:
import re
re.sub(r"(?<==).*",lambda m: m[0][::-1],s)
Out: 'srting=nga6ssg*d321'
(?<==) lookbehind ?<= for'='; so '=' isn't captured for replacing;
sub's 2nd arg can be a function, too, which got the match object, here 'm'.