Python,can';不要替换生成器对象

Python,can';不要替换生成器对象,python,generator,Python,Generator,我需要用空格替换字符串的标点符号。 问题是我需要在一行中完成 例如:有一个字符串:'H,+-=/e^@ll-!!。。o' 结果应该是:'H---e---ll---o' 其中'-'表示'(空格) 当我这样做的时候 replace((c for c in string.punctuation),' ') 我得到一个错误: TypeError: Can't convert 'generator' object to str implicitly 我试着把它写进一个列表,一套,甚至是一份口述。 但这

我需要用空格替换字符串的标点符号。 问题是我需要在一行中完成

例如:有一个字符串:
'H,+-=/e^@ll-!!。。o'

结果应该是:
'H---e---ll---o'

其中
'-'
表示
'
(空格)

当我这样做的时候

replace((c for c in string.punctuation),' ')
我得到一个错误:

TypeError: Can't convert 'generator' object to str implicitly
我试着把它写进一个列表,一套,甚至是一份口述。 但这一错误不断出现

我怎样才能超越它呢?

试试下面的方法

import string
''.join(map(lambda x : '-' if x in string.punctuation else x,
       'H,+-=/e^@#%ll-!!..o'))
试着跟随

import string
''.join(map(lambda x : '-' if x in string.punctuation else x,
       'H,+-=/e^@#%ll-!!..o'))
str.replace()。该方法将一个完整的字符序列替换为另一个,因此即使是
x.replace(string.puntuation,'-')
也只能用一个破折号替换
x
中出现的
字符串的整个标点

使用,而不是:

演示:

str.translate()
是将字符映射到其他字符或从字符串中删除字符的最快方法

在Python 3上,
str.translate()
(或在Python 2中,
unicode.translate()
)采用映射:

translationmap = {ord(c): '-' for c in string.punctuation}
x.translate(translationmap)
str.replace()。该方法将一个完整的字符序列替换为另一个,因此即使是
x.replace(string.puntuation,'-')
也只能用一个破折号替换
x
中出现的
字符串的整个标点

使用,而不是:

演示:

str.translate()
是将字符映射到其他字符或从字符串中删除字符的最快方法

在Python 3上,
str.translate()
(或在Python 2中,
unicode.translate()
)采用映射:

translationmap = {ord(c): '-' for c in string.punctuation}
x.translate(translationmap)
您还可以为此使用:

>>> from re import sub
>>> sub("\W", "-", "H,+-=/e^@#%ll-!!..o")
'H-----e----ll-----o'
>>>
捕获所有非单词字符


请注意,上面的代码将保留下划线。如果您不需要它们,请将
\W
替换为
[\W\u]

您也可以使用:

>>> from re import sub
>>> sub("\W", "-", "H,+-=/e^@#%ll-!!..o")
'H-----e----ll-----o'
>>>
捕获所有非单词字符



请注意,上面的代码将保留下划线。如果不需要,请将
\W
替换为
[\W\u]

而不是使用
映射和lambda,为什么不使用生成器表达式呢<代码>“”。连接(如果c不在字符串中,则为c。对于丑陋字符串中的c,则为标点符号,否则为“-”)
这也是一种方法。无论如何,我认为最优雅的方法是按照Martijn Pieters的建议使用翻译映射。与其使用
map
和lambda,为什么不使用生成器表达式呢<代码>“”。连接(如果c不在字符串中,则为c。对于丑陋字符串中的c,则为标点符号,否则为“-”)
这也是一种方法。不管怎样,我认为最优雅的方法是使用Martijn Pieters建议的翻译图。为什么你必须在一行中完成?为什么你必须在一行中完成?