在Python中从字符串中提取子字符串

时间:2016-02-20 02:21:32

标签: python string substring

我有一个看起来像这样的字符串:

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

我想打印出一个如下所示的字符串:

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

我尝试过:

catCount = ''

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

但是,该代码打印出来:

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

我怎样才能达到理想的效果?

4 个答案:

答案 0 :(得分:1)

import re

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

答案 1 :(得分:1)

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

答案 2 :(得分:0)

尝试一次

catCount = ''

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

答案 3 :(得分:0)

使用str.index,尤其是 start 参数。

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)