Home > OS >  Is there a way to extract two or more digit numbers out of a string?
Is there a way to extract two or more digit numbers out of a string?

Time:10-02

So i'm new in coding and I need to do something like this: x="f100r90f100...." (the numbers can be at most three digit numbers, and the only valid alphabetic characters are "fbrl"

output: [100,90,100,...]

I have searched for answers on this topic online and everyone brings up re library, but I can only do this with "vanilla" python, "for" and "while" loops and lists tuples etc. Could anyone help me?

CodePudding user response:

Try:

out = list(
    map(int, "".join(ch if "0" <= ch <= "9" else " " for ch in x).split())
)
print(out)

Prints:

[100, 90, 100]

EDIT: Version without map():

out = [
    int(num)
    for num in "".join(ch if "0" <= ch <= "9" else " " for ch in x).split()
]
print(out)

CodePudding user response:

A slightly roundabout way, but still within the bounds of "vanilla" Python:

Note: string is a builtin module, but there are various alternatives to this. For example, you could use str.isdigit() or check the ascii value like 48 <= ord(c) <= 57.

import string

_is_num = set(string.digits).__contains__


def get_digits(s):  # type: (str) -> list[int]
    digits = []
    num_start = False
    i_start = 0

    for i, c in enumerate(s):  # type: int, str
        if num_start:
            if not _is_num(c):
                num_start = False
                digits.append(int(s[i_start:i]))
        elif _is_num(c):
            num_start = True
            i_start = i

    if num_start:
        digits.append(int(s[i_start:]))

    return digits

Usage:

x = "f100r90f100e300"
print(get_digits(x))  # [100, 90, 100, 300]

CodePudding user response:

To improve on Andrej's answer:

out = list(
    map(int, "".join(ch if ch.isdigit() else " " for ch in x).split())
)
print(out)

CodePudding user response:

I hope this "vanilla" enough:

x = "f100r90f100"

tmp = []
for i in x:
    if i.isdigit():
        tmp.append(i)
    else:
        tmp.append(" ")

tmp = "".join(tmp).split()

xlist = []
for i in tmp:
    xlist.append(int(i))

print(xlist)

# [100, 90, 100]
  • Related