如何使用正则表达式的findall列表

2024-10-06 11:21:33 发布

您现在位置:Python中文网/ 问答频道 /正文

所以我是一名js实习生,在实习期间有人让我在python代码上做一些事情,但我从来没有在python上做过一些事情,所以我有点迷茫。。 我想在不同的块中分开一个字符串

以下是我所拥有的:

    buffer = """
#<start>
    idothings
#</start>
#<params>
    otherthings
#</params>
#<end>
    andifinish
#</end>

我想要的是一个正则表达式,它将这个字符串分成不同的部分:

separatedString = [["#<start>,"idothings","#</start>"],["#<params>,"otherthings","#</params>"],["#<end>,"andifinish","#</end>"]]

我想做的是:

def getStructure(string):

    separatedString = re.findall('(#<.+?>)(.|\n)+?(#<\/.+?>)', string)
    return

但这给了我一张单子。。。我不明白如何在python中浏览列表

[("#<start>", '\n', '#</start>'), ('#<azeaze>', '\n', '#</azeaze>'), ('#<sgdfs>', 'x', '#</sgdfs>')]

我试过:

print '\n'.join(["%s a %s et %s" %(p1,p2,p3) for p1, strings in separatedString ])

但它给了我一个错误“太多的值无法解包”

有人能告诉我怎么做吗


Tags: 字符串stringjsparams事情startendp1
2条回答
buffer = """#<start>
    idothings
#</start>
#<params>
    otherthings
#</params>
#<end>
    andifinish
#</end>"""

spl = buffer.splitlines()
print([spl[i:i+3] for i in range(0,len(spl),3)])
[['#<start>', '    idothings', '#</start>'], ['#<params>', '    otherthings', '#</params>'], ['#<end>', '    andifinish', '#</end>']]




spl = buffer.splitlines()
sliced = [spl[i:i+3] for i in range(0,len(spl),3)]

for a,b,c in sliced:
    print(a.strip(),b.strip(),c.striip())
('#<start>', 'idothings', '#</start>')
('#<params>', 'otherthings', '#</params>')
('#<end>', 'andifinish', '#</end>')

你的书面陈述有点错误 . 试试这个

print '\n'.join(["%s a %s et %s" %(p1,p2,p3) for p1, p2, p3 in separatedString ])

出现错误的原因是,您试图从包含三个元素的元组中获取两个值

for p1, strings in separatedString 

这里separatedString的每个成员中有3个元素

相关问题 更多 >