How NOT to separate a number of two or more digits when adding to a Python list?

Asked

Viewed 63 times

1

I have a problem that, when iterating over a string and adding only the numbers in a list, a number (for example 13) eventually becomes ['1', '3'].

How to get around this and make the number complete, as in ['13']?

Note that there is no space between digits to use the split.

teste = 'A2B4C13'

listaNumeros = []
for numero in teste:
   if numero.isnumeric():
     listaNumeros.append(numero)
    
print(listaNumeros)

3 answers

3

As an alternative to the other answer, I would give to do this relatively simply using a regular expression:

import re

nums = re.findall(r"\d+", "A2B4C13")
print(nums)  # ['2', '4', '13']

See working on Ideone.

Basically, the function is used findall (from the regular expression module) to search for any numerical occurrence in the string.

1


Instead of adding the character directly to the list, you can create a buffer variable to store the value while it is numeric and add the list only when you find a letter or finish the string:

teste = 'A2B4C13'

listaNumeros = []
buffer = ''

for numero in teste:
  if numero.isnumeric():
    buffer += numero
  elif buffer:
    listaNumeros.append(buffer)
    buffer = ''

if buffer:
  listaNumeros.append(buffer)
  buffer = ''
    
print(listaNumeros)  # ['2', '4', '13']

1

You wanted to save the numbers on a list? I did it that way did not use lists to join the characters

teste = 'A2B4C13'

listaNumeros = ""
listaDeLetras = ""
for numero in teste:
    if numero.isnumeric():
        listaNumeros += numero
    else:
        listaDeLetras += numero

print("Numeros:",listaNumeros)
print("Letras:"+listaDeLetras)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.