2017-04-10 180 views
2

我想分割字符串和數字。所以,如果是串聯的字符串是:Python中的單獨字符串和整數

Hans went to house number 10 92384 29349 

應該文本分成:

Hans went to house number | 10 | 92384 | 29349 

我很困惑如何解決這個因爲拆分將無法工作,因爲它也將拆分漢斯|去了|到|房子|數..

+0

你想它分割成一個列表或者只是添加|字符串? – citizen2077

回答

6

很容易使用正則表達式:

>>> import re 
>>> s = "Hans went to house number 10 92384 29349" 
>>> re.split(r'\s+(?=\d+\b)', s) 
['Hans went to house number', '10', '92384', '29349'] 

這就是說你的問題是混亂的,如果你想在|字符添加到輸出,只需再次加盟輸出:

>>> ' | '.join(_) 
'Hans went to house number | 10 | 92384 | 29349' 

如果你的目標是實現一個功能,可以這樣寫:

def split_numbers(string, join=None): 
    from re import split 
    split = re.split(r'\s+(?=\d+\b)', string) 
    return join.join(split) if join else split 

注意,我添加了字邊界\b我的正則表達式,以避免句子Hans went to house number 10 92384 29349 and drank 2cups of coffee

+0

正則表達式可能是解決此問題的最佳方法 – citizen2077

+0

假設理解正則表達式的工作原理很容易。而且它們很強大。但是定義一個並不容易;) – Matthias

0

這裏是你如何能做到這一點:

a = 'Hans went to house number 10 92384 29349' 

result = [' '.join([item for item in a.split(' ') if not item.isdigit()])] + [int(item) for item in a.split(' ') if item.isdigit()] 

如果你想輸出爲您呈現:

new_result = ' | '.join([str(item) for item in result]) 
+0

當你有一個例子如'a ='時,單詞的順序會改變。漢斯12去了門牌號碼10 92384 29349''。 – Michael

+0

是的。但這並不是例證。同樣的例子也會打破頂級投票的解決方案。 – zipa

3

如果你只是想添加|字符串,你可以試試這個:

a="Hans went to house number 10 92384 29349" 

print(" ".join("| "+i if i.isdigit() else i for i in a.split())) 

輸出:

Hans went to house number | 10 | 92384 | 29349 
2

您可以分割你的句子成詞開始與一些像2cups匹配單詞,然後嘗試字鑄成整數。如果轉換失敗,那麼就CONCAT

a = "Hans went to house number 10 92384 29349" 
res = "" 
for word in a.split(): 
    try: 
     number = int(word) 
     res += " | %d" % number 
    except ValueError: 
     res += " %s" % word 

編輯:我試着給了 「最簡單」 的解決方案。我的意思是,時間更長,但我認爲更容易理解。儘管如此,如果你瞭解其他解決方案(1行),就去做吧。

2

使用正則表達式分裂與re

import re 


txt = 'Hans went to house number 10 92384 29349' 

' | '.join(re.split('\s(?=\d)',txt)) 

# 'Hans went to house number | 10 | 92384 | 29349' 
0

你可以這樣做:

a = "Hans went to house number 10 92384 29349" 

res = [] 

for item in a.split(): 
    if item.isdigit(): 
     res.extend(['|', item]) 
    else: 
     res.append(item) 

print(' '.join(res)) 
#Hans went to house number | 10 | 92384 | 29349