[英]python split string every x characters but except space
here is my code这是我的代码
string = '얼굴도 잘 생긴데다 학력에 집안에~ 뭐 뒤쳐지는게 없잖아. 조건이 워낙 좋아야말이지'
n = 10
split_string = [string[i:i+n] for i in range(0, len(string), n)]
and this is the result I want.这就是我想要的结果。 what should I do?我应该怎么办?
split_string = ['얼굴도 잘 생긴데다 학력', '에 집안에~ 뭐 뒤쳐지는', '게 없잖아. 조건이 워낙',
' 좋아야말이지']
I have tried to implement your described problem and made assumptions where I was not fully sure about the expected behavior of the program.我试图实现您描述的问题,并在我不完全确定程序的预期行为的情况下做出假设。 I assumed that you want to split the string into substrings such that each substring contains at least 10 non-space characters excluding trailing spaces.我假设您想将字符串拆分为子字符串,以便每个子字符串包含至少 10 个非空格字符,不包括尾随空格。 The concatenation of the susbtrings yields the initial input.子串的串联产生初始输入。 Note that a width of 0 yields an endless loop and an empty input yields an empty substring (given that width > 0).请注意,宽度为 0 会产生无限循环,而空输入会产生空子字符串(假设宽度 > 0)。
For the snippet below, I have replaced your input ( string
) and substring length ( n
) with a simpler example.对于下面的代码片段,我用一个更简单的示例替换了您的输入 ( string
) 和子字符串长度 ( n
)。 Using your instead instead yields your expected result.使用您的代替会产生您预期的结果。
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.