2017-07-12 36 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

這不正確處理括號。 –