我有一个看起来像这样的字符串:
s = "asd[123]348dsdk[45]sdhj71[6789]sdfh"
我需要另一个包含这样的数字的字符串:
s_filter = "123 45 6789"
很抱歉没有发布我自己的想法! 我试图用这个:
s = "asd[123]348dsdk[45]sdhj71[6789]sdfh"
s_filter = s[s.find("[")+1:s.find("]")]
result: s_filter = "123"
但是它只给我第一个数字。
有什么想法吗?
最好, 汉斯
答案 0 :(得分:1)
简单的if / elif语句可以做到:
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)
输出:
123456789
答案 1 :(得分:1)
正则表达式可以做到这一点:
s = "asd[123]348dsdk[45]sdhj71[6789]sdfh"
import re
s_filter = ' '.join(re.findall(r"\[(\d+)\]",s)))
print(s_filter)
输出:
123 45 6789
模式说明:
\[ \] are the literal square brackets
(\d+?) as as few numbers inside them as capture group
re.findall
找到它们全部,然后' '.join(iterable)
将它们组合成字符串。