2017-07-12 34 views
1

从字符串中删除不同字符的简洁方法是什么?例如,我有以下字符串,我需要转换为整数:删除字符串中字符的Pythonic方法

($12,990) 
$21,434 

我用下面的代码工作正常,但有一个不太笨重的方式做?

string = string.replace(",", "") 
string = string.replace("$", "") 
string = string.replace("(", "-") 
string = string.replace(")", "") 
int(string) 

编辑:我正在使用Python 2.7。

+0

是'与string.replace( “(”,“ - “)'错字?这条线不会删除一个字符... – MSeifert

+1

@ MSeifert这是Excel格式的负数将括号括起来 –

+0

[This answer](https://stackoverflow.com/a/15448887/223424)最简洁,但整个线程非常好,并且表明问题并非完全无关紧要。 – 9000

回答

3

你可以使用str.translate,例如

>>> "($12,990)".translate(str.maketrans({',': '', '$': '', '(': '-', ')': ''})) 
'-12990' 

正如评论由@AdamSmith说,你也可以利用的str.maketrans的(全)三个参数的形式:

>>> translationtable = str.maketrans("(", "-", ",$)") 
>>> "($12,990)".translate(translationtable) 
'-12990' 

如果您正在使用python-2。 x中的str.translate功能和string.maketrans函数可用于:

>>> import string 
>>> translationtable = string.maketrans('(', '-') 
>>> "($12,990)".translate(translationtable, ',$)') 
'-12990' 

或与统一码对Python的2.x的,你需要一个Unicode的顺序为Unicode-序/字符串或无:

>>> unicode_translation_table = {ord(u','): None, ord(u'$'): None, ord(u'('): ord(u'-'), ord(u')'): None} 
>>> u"($12,990)".translate(unicode_translation_table) 
u'-12990' 
+1

或'str.maketrans(“(”,“ - ”,“,$)”)'[per文档](https://docs.python.org/3/library/stdtypes.html#str.maketrans)'maketrans'的三参数版本将前两个参数配对,并将第三个参数映射到'None'(空字符串) –

+0

我收到一个错误'AttributeError:type object'str'has no attribute'maketrans''。我想这是因为我使用Python 2.7。有没有办法让它在Python 2.7中工作? – sprogissd

+0

@sprogissd我包括解决它的蟒蛇2.7的方式:) – MSeifert

0

好了,你可以依靠一个循环,使它不那么难看:

FORBIDDEN_CHARS = { # Model: { "Replacer" : "Replacees", ... } 
"" : ",$)", 
"-" : "(" 
} 

for replacer in FORBIDDEN_CHARS: 
for replacee in FORBIDDEN_CHARS[replacer]: 
    mystr = mystr.replace(replacee, replacer) 
+0

对不起,你可以依靠联想字典,让我更新 – Fabien

+0

更新:-)现在听起来正确 – Fabien

-1
''.join(string.strip('(').strip(')').strip('$').split(',')) 

''.join(filter(str.isdigit, string)) 
+1

这不正确处理括号。 –