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. 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).
For the snippet below, I have replaced your input ( string
) and substring length ( n
) with a simpler example. 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(" ", "")
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.