在[n]个字符后插入字符串并删除其余的字符串

时间:2018-08-02 14:43:10

标签: python regex string

我有一个字符串srting=123d*gss6agn 我如何删除=之后的所有内容并留空 我应该使用re还是string模块,我该怎么解决

3 个答案:

答案 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'.