簡體   English   中英

拆分字符串,只在python中獲取數字?

[英]Split string and just get number in python?

我有一個字符串,如"GoTo: 7018 6453 12654\\n"我只想得到像這樣的數字['7018', '6453', '12654'] ,我嘗試正則表達但我不能拆分字符串得到這里的數字是我的代碼:

樣本1:

splitter = re.compile(r'\D');
match1 = splitter.split("GoTo: 7018 6453 12654\n")

my output is: ['', '', '', '', '', '', '', '', '7018', '6453', '12654', '']

樣本2:

splitter = re.compile(r'\W');
match1 = splitter.split("GoTo: 7018 6453 12654\n")

my output is: ['GoTo', '', '7018', '6453', '12654', '']

如果所有數字都是正整數,則可以使用isdigit()方法在沒有正則表達式的情況下執行此操作:

>>> text = "GoTo: 7018 6453 12654\n"
>>> [token for token in text.split() if token.isdigit()]
['7018', '6453', '12654']
>>> re.findall(r'\d+', 'GoTo: 7018 6453 12654\n')
['7018', '6453', '12654']
>>> import re
>>> re.findall("[0-9]+", "GoTo: 7018 6453 12654\n")
['7018', '6453', '12654']
>>> 

您可以按照示例1中的當前方法以及此代碼:

filter (lambda a: a != '', match1)

嘗試這個:

import re
splitter = re.compile(r'\d+')
match1 = splitter.findall("GoTo: 7018 6453 12654\n")
print match1

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM