Home > Software design >  move numbers out of a string?
move numbers out of a string?

Time:10-02

So i'm new in coding and I need to do something like this: x="rtx2080gtx1050i8100...."

output: [2080,1050,8100,...] 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