【问题标题】:Replace String in python with a sequence of Alphabet [duplicate]用字母序列替换python中的字符串[重复]
【发布时间】:2017-02-18 01:02:26
【问题描述】:

我正在编写一段 python 代码来替换一个字母序列。我知道该怎么做,但不幸的是它只是替换了已经替换的那个。

lines=[]
replacements = {'a':'s','s':'d','d':'f','f':'g','g':'h','h':'j','j':'k','k':'l'}

with open("wrongString.txt") as infile:
    for line in infile:
        for src,target in replacements.iteritems():
            line = line.replace(src,target)
        lines.append(line)

with open("decode.txt","w") as outfile:
        for line in lines:              
            outfile.write(line)

wrongstring.txt : asdfghjkl

运行代码后,结果显示(encode.txt):ggggkkkll

代码确实将“a”替换为“s”,并不断将“s”替换为“d”,直到以某种方式得到“g”。我只想将“a”替换为“s”然后停止替换它。

你们能帮我找到解决办法吗?

感谢您的回答!

【问题讨论】:

    标签: python string python-2.7 replace str-replace


    【解决方案1】:

    使用 list comp 这样您就不会覆盖任何替换的字符:

      line = "".join([replacements.get(ch, ch) for ch in line])
    

    你也不需要存储所有的行,只要你去写行:

    with open("wrongString.txt") as infile, open("decode.txt","w")  as outfile:
        outfile.writelines("".join([replacements.get(ch,ch) 
                                      for ch in line]) for  line in infile))
    

    【讨论】:

    • 不错!它就像一个魅力:D。非常感谢
    猜你喜欢
    • 1970-01-01
    • 2020-04-13
    • 2015-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-03-01
    • 2018-12-12
    • 2016-06-06
    相关资源
    最近更新 更多