python - python每隔x个字符拆分字符串,但空格除外
问题描述
这是我的代码
string = '얼굴도 잘 생긴데다 학력에 집안에~ 뭐 뒤쳐지는게 없잖아. 조건이 워낙 좋아야말이지'
n = 10
split_string = [string[i:i+n] for i in range(0, len(string), n)]
这就是我想要的结果。我应该怎么办?
split_string = ['얼굴도 잘 생긴데다 학력', '에 집안에~ 뭐 뒤쳐지는', '게 없잖아. 조건이 워낙',
' 좋아야말이지']
解决方案
我已尝试实施您描述的问题,并在我不完全确定程序的预期行为的情况下做出假设。我假设您要将字符串拆分为子字符串,以便每个子字符串至少包含 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']
推荐阅读
- arrays - 在循环中将数据行存储在数组中
- arrays - 在 2D numpy id 数组中搜索部分 id
- c - 显示数字而不是用户数据的 C 结构
- java - 是否可以从 DB 添加 logback.xml 配置值?
- c# - 如何提高 UWP 语音识别框架的准确率?
- python - logrotate 后日志开头的空值
- qt - 如何将字符串作为 QTextEdit 信号的参数传递
- c# - 无法在团队中创建多个私人频道
- android - 生成签名的 apk 时出错:com.google.gson.ExclusionStrategy 类型已定义多次
- python - 检索 JSON 查询结果后代码中断