如何在字符列表中循环并用“替换”替换它们_&引用;用Python?
我试图让我的Python程序循环遍历我在列表中编写的不需要的字符列表。我希望它使用for函数将这些字符替换为字符串中的“\u1”如何在字符列表中循环并用“替换”替换它们_&引用;用Python?,python,string,Python,String,我试图让我的Python程序循环遍历我在列表中编写的不需要的字符列表。我希望它使用for函数将这些字符替换为字符串中的“\u1” global string global OddChars string = "Parenthesis: () Brackets: []" OddChars = ["[", "]", "(", ")", " "] for Replace in OddChars: string = string.replace(Replace, "_") print (
global string
global OddChars
string = "Parenthesis: () Brackets: []"
OddChars = ["[", "]", "(", ")", " "]
for Replace in OddChars:
string = string.replace(Replace, "_")
print (string)
我希望新字符串具有u而不是()[]和空格。
当我尝试这个方法时,它不起作用,它会打印与以前相同的字符串
>>> s = "Parenthesis: () Brackets: []"
>>> o = ["[", "]", "(", ")", " "]
>>> "".join(["_" if c in o else c for c in s])
'Parenthesis:____Brackets:___'
对于这种类型的操作,请使用
str.translate
方法
Python 2
在Python 2中,我们使用string
模块的maketrans
函数来创建翻译表。(请确保不要覆盖string
模块,我已将变量名string
更改为下面的mystring
。)
Python 3
在Python 3中,string
模块没有此功能,它已作为静态方法移动到内置的str
(这意味着您可以从str
或字符串实例调用它,如下面的my_string
):
函数可以如下所示:
def replace_chars(my_string, old_chars, new_chars):
return my_string.translate(str.maketrans(old_chars, new_chars))
我试图纠正你的解决办法。你的逻辑有点不正确。在第一次替换之后,您没有在迭代中传递其他奇数字符的更新字符串。这对我在空闲状态下有效,没有
global
声明。我认为您存在范围问题。全局字符串是在函数外部还是在函数内部?向我们展示在运行时演示问题的可运行代码。是的,我现在就开始工作了。我想我的空闲时间太长了。@user3024151我下面的答案对你有用吗?或者“”。join(如果我不在OddChars中,那么我在list(string)中为I添加“u”)
声明性的,就像python一样,我建议扩展你的答案以包含一些解释性的英文文本。在Python3中,你不导入string
。只需使用str.maketrans()
代替即可。感谢@gnibbler让我注意到这一点。我现在已经谈到这个问题。
import string
def replace_chars(my_string, old_chars, new_chars):
translation_table = string.maketrans(old_chars, new_chars)
return my_string.translate(translation_table)
>>> my_string = "Parenthesis: () Brackets: []"
>>> translation_table = str.maketrans('[]() ', '_____') # str could be my_string
>>> translation_table
{40: 95, 41: 95, 91: 95, 93: 95, 32: 95}
>>> my_string.translate(translation_table)
'Parenthesis:____Brackets:___'
def replace_chars(my_string, old_chars, new_chars):
return my_string.translate(str.maketrans(old_chars, new_chars))
>>> input_string = "Parenthesis: () Brackets: []"
>>> temp_string = ''
>>> odd_chars = ["[", "]", "(", ")", " "]
>>> for odd_char in odd_chars:
... temp_string = input_string.replace(odd_char, "_")
... input_string = temp_string
...
>>> print input_string
Parenthesis:____Brackets:___