![](/img/trans.png)
[英]How to extract numbers and characters from a string Python pandas?
[英]Python extract numbers from string of alphanumeric characters
如何在Python中將數字打印在字符串中? 在下面的示例中,我可以打印6。如何一起打印6和5? 給我65。
man = 'The man is 65 or older'
print(man[11])
我可以想到兩種不涉及對索引進行硬編碼的方法。
str.split
進行str.isdigit
numbers = [x for x in string.split() if x.isdigit()]
print(numbers)
['65']
re.findall
import re
numbers = re.findall(r'\b\d+\b', string)
print(numbers)
['65']
正則表達式詳細信息
\b # word boundary
\d+ # match 1 or more digits
\b # word boundary
請注意,如果只想返回不屬於較大單詞的數字,則應使用\\b
單詞邊界(例如,此處不計算3D
)。
這個短代碼怎么樣?
man = 'The man is 65 or older'
numbers = list(filter(str.isdigit, man.split(' ')))
print(numbers[0])
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.