1. 程式人生 > >Python3中字符串中的數字提取方法

Python3中字符串中的數字提取方法

lag none alc repl ota pre [1] total 一個

Python3中字符串中的數字提取方法

  • re.sub(pattern, repl, string, count=0, flags=0)
1 totalCount = '100abc'
2 totalCount = re.sub("\D", "", totalCount)
  • str.split(sep=None, maxsplit=-1)
>>> import string
>>> a = "32 個答案"
>>> b = a.split()[0]
>>> print(b)
>>> type(b)
<class 'str'>
>>> c = '1,2,3'
>>> c.split(',')
['1', '2', '3']
>>> c.split(',')[0]
'1'
>>> c.split(',')[1]
'2'
>>>

split()的第一個參數是分隔符,如果什麽都不填就是默認是以空格來分隔

Python3中字符串中的數字提取方法