簡體   English   中英

在 Python 中將數字與文本分開

[英]Separate digits from text in Python

我正在嘗試將數字與 Python 中的字符串分開,例如以下示例:

text = "Compute the average of 5,7". (I want to get a list [5,7])

(數字之間的逗號是必須的)我試過使用:

numbers = [int(i) for i in text.split() if i.isdigit()]

當數字沒有用逗號分隔時它起作用,但是當用逗號書寫時,我只收到一個空列表。

使用正則表達式查找以逗號分隔的兩個整數。

import re

m = re.search(r'(\d+),(\d+)', text)
if m:
    numbers = [int(x) for x in m.groups()]

嘗試這個:

text = "Compute the average of 5,7"
nums = [int(i) for i in text if i.isdigit()]
print(nums)
# prints [5, 7]
>>> import re
>>> re.search('.*(\d,\d).*', text).group(1)
'5,7'

暫無
暫無

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

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