-10

i have a string looking like this:

s = "asd[123]348dsdk[45]sdhj71[6789]sdfh"

i need an other string that contains the numbers in brackets like this:

s_filter = "123 45 6789"

Sorry for not posting my own ideas! i tried to use this:

s = "asd[123]348dsdk[45]sdhj71[6789]sdfh"
s_filter = s[s.find("[")+1:s.find("]")]

result: s_filter = "123"

But it only gives me the first numbers.

Any ideas?

Best, Hans

Hans Müller
  • 1
  • 1
  • 3
  • please make an attempt and share your attempt before asking, SO is not a coding service – depperm Sep 05 '18 at 16:50
  • Please check https://stackoverflow.com/questions/4666973/how-to-extract-a-substring-from-inside-a-string-in-python – Dharmesh Sep 05 '18 at 16:56

2 Answers2

1

Regex can do that:

s = "asd[123]348dsdk[45]sdhj71[6789]sdfh"
import re
s_filter  = ' '.join(re.findall(r"\[(\d+)\]",s)))

print(s_filter)

Output:

123 45 6789

Pattern explained:

\[         \]   are the literal square brackets
    (\d+?)      as as few numbers inside them as capture group

re.findall finds them all and ' '.join(iterable)combines them back into a string.

Patrick Artner
  • 50,409
  • 9
  • 43
  • 69
0

Simple if/elif statment will do it:

s = "asd[123]348dsdk[45]sdhj71[6789]sdfh"

s_filter = ""
x = False
for i in s:
    if i == "[": x = True
    elif i == "]": x = False
    elif x: s_filter += i

print(s_filter)

Output:

123456789
tgikal
  • 1,667
  • 1
  • 13
  • 27