使用line.replace()和空格时的Python问题

使用line.replace()和空格时的Python问题,python,python-2.7,Python,Python 2.7,我目前正在处理几行代码,希望用符号“]”替换符号分号“;”。我使用的是line.replace(“;”,“]”)。不知何故,我发现当分号在一行中的位置不一致时,它就不起作用了 例如: input add_clk; #this one works where the output will be input add_clk] 但是,它不适用于以下行: input sub_clk ; #tnothing change to the output, input sub_clk 我在脚本中使用的行是

我目前正在处理几行代码,希望用符号“]”替换符号分号“;”。我使用的是line.replace(“;”,“]”)。不知何故,我发现当分号在一行中的位置不一致时,它就不起作用了

例如:

input add_clk; #this one works where the output will be input add_clk]
但是,它不适用于以下行:

input sub_clk ; #tnothing change to the output, input sub_clk
我在脚本中使用的行是:

if ";" in line:
    line = line.replace(";","]")

不知怎的,我发现这个问题可能是因为分号前面有空格。脚本是否可以忽略空格,以便输出为输入sub_clk]?

您的代码在我的电脑中运行正常。您可以尝试从输入中删除空格:

l = input()
if ";" in l:
    l = l.replace(";","]").replace(" ","")
print(l)

您的代码在我的终端上工作:

>>> a = "input sub_clk ;"
>>> if ";" in a:
...     a = a.replace(";", "]")
... 
>>> a
'input sub_clk ]'
>>> 
也许字符串中有一些不可见的字符?至少,我看不到您的代码中有任何问题

如果要替换分号并删除其前面的空格,可以尝试如下操作:

>>> import re
>>> a = "input sub_clk ;"
>>> a = a.rstrip()
>>> a = re.sub("\\s*;$","]",a)
>>> a
'input sub_clk]'

我无法重现这个问题。请提供一个。嗨,我试过使用你的解决方案它的工作。非常感谢!!你说得对,也许我的字符串中有一些看不见的字符。