Helloimjs0n
Helloimjs0n

Reputation: 67

Extracting substring from string in Python

I have a string that looks like this:

catString = randomtextrandomtext (cats:1)=1 randomtext randomtextrandomtext (cats:3)=3 randomtext randomtext (cats:1540)=1,540 randomtextrandomtext randomtext (cats:85):85 randomtext

I want to print out a string that looks like this:

(cats:1)(cats:3)(cats:1540)(cats:85)

I tried doing:

catCount = ''

for a in catString:
    for b in line.split():
        if '(cats:' in b:
            catCount += str(part)
print catCount

However, that code prints out:

(cats:1)=1(cats:3)=3(cats:1540)=1,540(cats:85)=85

How can I achieve my desired result?

Upvotes: 0

Views: 90

Answers (4)

helloV
helloV

Reputation: 52393

import re

''.join(re.findall(r'\(cats:\d*\)', catString))

Upvotes: 1

Tony Babarino
Tony Babarino

Reputation: 3405

>>> ''.join(re.findall('\(cats:[0-9]+\)',catString)) 
'(cats:1)(cats:3)(cats:1540)(cats:85)'

Upvotes: 1

aghast
aghast

Reputation: 15310

Use str.index and particularly the start parameter.

catString = "randomtextrandomtext (cats:1)=1 randomtext randomtextrandomtext (cats:3)=3 randomtext randomtext (cats:1540)=1,540 randomtextrandomtext randomtext (cats:85):85 randomtext"

result = ''
end = -1
try:
    while True:
        start = catString.index('(cats:', end+1)
        end = catString.index(')', start)
        result += catString[start:end+1]

except ValueError:
    pass

print(result)

Upvotes: 0

Jyothi Babu Araja
Jyothi Babu Araja

Reputation: 10292

Try this once

catCount = ''

for a in catString:
    for b in line.split():
        if '(cats:' in b:
            catCount += str(b[0,b.index(")")+1])
print catCount

Upvotes: 0

Related Questions