Come catturo il primo elemento numerico in una stringa in Python? [duplicare]

Oct 30 2020

Ho il codice seguente

import re
age = []

txt = ('9', "10y", "4y",'unknown')
for t in txt:
    if t.isdigit() is True:
        age.append(re.search(r'\d+',t).group(0))
    else:
        age.append('unknown')
print(age)

e ottengo: ["9", "unknown", "unknown", "unknown"]

Quindi il 9 ottengo, ma devo anche prendere il 10 in seconda posizione, il 4 in terza e sconosciuto per ultimo.
Qualcuno può indicarmi la giusta direzione? Grazie per l'aiuto!

Risposte

2 Erfan Oct 30 2020 at 05:35

Possiamo sfruttare il fatto che re.searchrestituisce Nonequando non si trova alcuna cifra:

txt = ('9', "10y", "4y",'unknown')
age = []
for t in txt:
    num = re.search('\d+', t)
    if num:
        age.append(num.group(0))
    else:
        age.append('unknown')
['9', '10', '4', 'unknown']

Dato che hai taggato pandas, se hai una colonna, usa str.extract:

pd.Series(txt).str.extract('(\d+)')
0      9
1     10
2      4
3    NaN
dtype: object

sahasrara62 Oct 30 2020 at 05:39
import re
age = []

txt = ('9', "10y22", "4y", 'unknown')

for t in txt:
    res = re.findall('[0-9]+', t)
    if res:
        age.append(res[0])
    else:
        age.append("unknown")
dippie Oct 30 2020 at 05:49
import re


age = []

txt = ('9', "10y", "4y",'unknown')
for t in txt:
    if len(t) > 1 and not t.isdigit():
        t = t.replace(t[-1], '')
    if t.isdigit() is True:
        age.append(re.search(r'\d+',t).group(0))
    else:
        age.append('unknown')
print(age)

Controllalo. Quindi la funzione len controlla se la stringa è più grande di uno e quindi se l'ultima lettera della stringa non è una cifra, l'ultima lettera della stringa viene sostituita con uno spazio vuoto. E poi segue il resto del tuo algoritmo. Puoi modificarlo di più per soddisfare le tue esigenze, poiché non hai specificato molto.