2016-08-01 36 views
-5

與字母混合卸下數字假設我有一個字符串,如:從字符串

string = 'This string 22 is not yet perfect1234 and 123pretty but it can be.' 

我想刪除任何數字這是用言語混合,如'perfect1234''123pretty'但不'22'從我的字符串,並得到一個輸出如下:

string = 'This string 22 is not yet perfect and pretty but it can be.' 

有沒有辦法使用正則表達式或任何其他甲基做到這一點在Python OD?任何幫助,將不勝感激。謝謝!

+1

用'''替換所有的'\ d +'' – Tushar

+0

請看這裏:http://stackoverflow.com/questions/12851791/removing-numbers-from-string – danielhadar

+1

似乎OP想要消除只是數字的一部分字,而不是字符串中的任何數字。 (單詞邊界事項) – Keozon

回答

1
import re 
re.sub(r'\d+', '', string) 
+0

應該爲正則表達式'r'\ d +'使用原始字符串文字,並且不檢查數字是否也包含字母字符(這似乎是意圖)的一部分。 – Keozon

+0

@Keozon是的,原始字符串更好,我會改變我的答案。但是,你的意思是「數字是單詞的一部分」,你能舉一個例子嗎? – kxxoling

+0

謝謝你的幫助!我不想保留任何在我的字符串中有以下格式的東西:'700/- ' ,'+91 1234567891','3appeared','Vora02261794300Will'。例子中的最後兩個數字或單詞不應出現在字符串中。 – PJay

3
s = 'This string 22 is not yet perfect1234 and 123pretty but it can be.' 

new_s = "" 
for word in s.split(' '): 
    if any(char.isdigit() for char in word) and any(c.isalpha() for c in word): 
     new_s += ''.join([i for i in word if not i.isdigit()]) 
    else: 
     new_s += word 
    new_s += ' ' 

而作爲一個結果:

'This string 22 is not yet perfect and pretty but it can be.' 
+0

比正則表達式(IMO)更復雜,但可能更快Python。很好的回答,我認爲更有針對性的OP的原意。 – Keozon

0

下面的代碼檢查每個字符爲一位數字。如果它不是數字,則將該字符添加到更正的字符串的末尾。

string = 'This string is not yet perfect1234 and 123pretty but it can be.' 

CorrectedString = "" 
for characters in string: 
    if characters.isdigit(): 
     continue 
    CorrectedString += characters 
+0

Thank you!This Works! – PJay

0

您可以通過簡單地加入功能試試這個,還有什麼可導入

str_var='This string is not yet perfect1234 and 123pretty but it can be.' 

str_var = ''.join(x for x in str_var if not x.isdigit()) 
print str_var 

輸出:

'This string is not yet perfect and pretty but it can be.' 
+1

非常感謝!這應該有所幫助! – PJay

2

如果您想保留它們本身的數字(不這個正則表達式將完成這項工作(但可能有一種方法可以使它更簡單):

import re 
pattern = re.compile(r"\d*([^\d\W]+)\d*") 
s = "This string is not yet perfect1234 and 123pretty but it can be. 45 is just a number." 
pattern.sub(r"\1", s) 
'This string is not yet perfect and pretty but it can be. 45 is just a number.' 

在這裏,剩下45是因爲它不是單詞的一部分。