[英]python split string every x characters but except space
这是我的代码
string = '얼굴도 잘 생긴데다 학력에 집안에~ 뭐 뒤쳐지는게 없잖아. 조건이 워낙 좋아야말이지'
n = 10
split_string = [string[i:i+n] for i in range(0, len(string), n)]
这就是我想要的结果。 我应该怎么办?
split_string = ['얼굴도 잘 생긴데다 학력', '에 집안에~ 뭐 뒤쳐지는', '게 없잖아. 조건이 워낙',
' 좋아야말이지']
我试图实现您描述的问题,并在我不完全确定程序的预期行为的情况下做出假设。 我假设您想将字符串拆分为子字符串,以便每个子字符串包含至少 10 个非空格字符,不包括尾随空格。 子串的串联产生初始输入。 请注意,宽度为 0 会产生无限循环,而空输入会产生空子字符串(假设宽度 > 0)。
对于下面的代码片段,我用一个更简单的示例替换了您的输入 ( string
) 和子字符串长度 ( n
)。 使用您的代替会产生您预期的结果。
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']
对列表使用 for 循环并使用类似split_string[i] = split_string[i].replace(" ", "")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.