Paulina
Paulina

Reputation: 159

turning string into a mixed list of chars and digits

how to make a string like this: '20P20P20P20' into a list like this [20, 'P', 20, 'P', 20, 'P', 20]

my_string = '20P20P20P20'
list_of_steps = list(my_string)
    for step in list_of_steps:
        if step.isdigit():
            new_map.append(int(step))
        else:
            new_map.append(step)

It turns into a digit, but how to join digits that are next to each other into one?

Upvotes: 0

Views: 28

Answers (2)

mkrieger1
mkrieger1

Reputation: 23209

Don't append each digit to new_map right away. First collect them in a temporary list until you find a letter again. Then combine the digits in the temporary list to a complete number and append that number to new_map.

Don't forget to clear the temporary list before you collect the next set of digits.

For example:

  • '2': append to temporary list, it is now ['2']
  • '0': append to temporary list, it is now ['2', '0']
  • 'P': convert temporary list ['2', '0'] to the number 20
    • append 20 to new_map
    • append 'P' to new_map
    • clear temprary list, it is now []
  • '2': append to temporary list, it is now ['2']
  • and so on...

For converting the temporary list of digits to a number, see Joining a list of string digits to create an integer Python 3.

Upvotes: 1

trincot
trincot

Reputation: 350477

You could use a regular expression to split the string into chunks.

import re

my_string = '20P20P20P20'
lst = [
    int(part) if part.isdigit() else part
    for part in re.findall(r"\d+|\D+", my_string)
]

Upvotes: 2

Related Questions