我想分割字符串和數字。所以,如果是串聯的字符串是:Python中的單獨字符串和整數
Hans went to house number 10 92384 29349
應該文本分成:
Hans went to house number | 10 | 92384 | 29349
我很困惑如何解決這個因爲拆分將無法工作,因爲它也將拆分漢斯|去了|到|房子|數..
我想分割字符串和數字。所以,如果是串聯的字符串是:Python中的單獨字符串和整數
Hans went to house number 10 92384 29349
應該文本分成:
Hans went to house number | 10 | 92384 | 29349
我很困惑如何解決這個因爲拆分將無法工作,因爲它也將拆分漢斯|去了|到|房子|數..
很容易使用正則表達式:
>>> 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
正則表達式可能是解決此問題的最佳方法 – citizen2077
假設理解正則表達式的工作原理很容易。而且它們很強大。但是定義一個並不容易;) – Matthias
這裏是你如何能做到這一點:
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])
如果你只是想添加|
字符串,你可以試試這個:
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
您可以分割你的句子成詞開始與一些像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行),就去做吧。
使用正則表達式分裂與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'
你可以這樣做:
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
你想它分割成一個列表或者只是添加|字符串? – citizen2077