对char进行拆分,但保留char python

2024-04-25 23:49:58 发布

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

当特定字符发生时,我想分割一个字符串(例如:。,!等) 我已经编写了split函数,它确实拆分,但删除了这些字符。 当我调用函数时,例如:

text = 'The first line leads off, With a gap before the next. Then the poem ends.'

我明白了

^{pr2}$

需要更改哪些内容才能不删除字符?我会得到这个:

^{pr3}$

我是说。

^{pr4}$

谢谢。


Tags: the函数字符串textwithline字符first
3条回答

只需使用正则表达式:

import re

text = 'The first line leads off, With a gap before the next. Then the poem ends.'
print re.findall('.*?[,.!]?', text)
# ['The first line leads off,', ' With a gap before the next.', ' Then the poem ends.']
def splitOnChars(text, chars):
    answer = []
    start = 0
    for i,char in enumerate(text):
        if char in chars:
            answer.append(text[start:i+1])
            start = i+1
    answer.append(text[i+1:])
    return answer

输出:

^{pr2}$

或者您可以忘记为此编写自己的函数并使用重新分割还有拉链。重新分割将在使用捕获组时将结果列表中的分隔符保留为下一个元素。可以使用两个不同的步骤迭代和zip将其连接起来。在

import re
mypoem = 'The first line leads off, With a gap before the next. Then the poem ends.'

junk = re.split("(,|\.)", mypoem)
poem_split = [i1 + i2 for i1, i2 in zip(junk[0::2], junk[1::2])]

相关问题 更多 >