首页 > 解决方案 > python每隔x个字符拆分字符串,但空格除外

问题描述

这是我的代码

    string = '얼굴도 잘 생긴데다 학력에 집안에~ 뭐 뒤쳐지는게 없잖아. 조건이 워낙 좋아야말이지'
    n = 10
    split_string = [string[i:i+n] for i in range(0, len(string), n)]
    

这就是我想要的结果。我应该怎么办?

split_string = ['얼굴도 잘 생긴데다 학력', '에 집안에~ 뭐 뒤쳐지는', '게 없잖아. 조건이 워낙', 
                     ' 좋아야말이지']

标签: pythonstring

解决方案


我已尝试实施您描述的问题,并在我不完全确定程序的预期行为的情况下做出假设。我假设您要将字符串拆分为子字符串,以便每个子字符串至少包含 10 个非空格字符,不包括尾随空格。子串的串联产生初始输入。请注意,宽度为 0 会产生无限循环,而空输入会产生空子字符串(假设宽度 > 0)。

对于下面的片段,我用一个更简单的示例替换了您的输入 ( string) 和子字符串长度 ( )。n改为使用 your 会产生预期的结果。

string = 'aaa b b b cc  c ee'
width = 3
split_string = []
_from = 0
_to = 0

while True:
    # we have reached the end of the string
    if len(string) +1 == _to:
        split_string += [string[_from:_to]]
        break
    # the substring contains a sufficient number of non-space characters
    if len(string[_from:_to].replace(" ", "")) == width:
        split_string += [string[_from:_to]]
        _from = _to
        continue
    # increase the length of the substring
    _to += 1

print(split_string)
# OUTPUT
# ['aaa', ' b b b', ' cc  c', ' ee']

推荐阅读