python - 在用户输入的某些点处切片和添加换行符的正确方法
问题描述
我有一个正在进行的程序,其中一个功能是获取一个可能很长的用户提供的字符串。但是,我需要确保字符串在某些点断开。我希望每行不超过 50 个字符,但必须在空格处中断。
对我来说似乎有意义的事情是运行一个 if 函数来测试字符串的长度,将其切成 50 个字符的长度,找到最后一个空格,然后在该点插入一个换行符。对我来说,这让代码看起来很笨拙。有没有更流畅、更 Pythonic 的方式来做到这一点?
instr = input()
if len(instr) > 50:
n = instr[:50].rfind(' ')
instr.replace(instr[n], "\n")
n += 50
if len(instr) > n:
n = instr[:n].rfind(' ')
instr.replace(instr[n], "\n")
n += 50
如您所见,该循环可能会一直持续下去,尽管如果它超过一定长度,我会让它生成一条错误消息。这段代码可以满足我的要求,但是有更好的方法吗?
解决方案
我参加聚会有点晚了,但这里有一个解释过的自动换行脚本,演示了如何编写一个。
我把最后几句话结合起来做了一个很长的词来展示它处理这个问题。
希望你觉得这个有用 :)
string = "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident,suntinculpaquiofficiadeseruntmollitanimidestlaborum."
length = 50
# split text into words
words = string.split(" ")
new = ""
for word in words:
# Calculate length of current line
current_length = len(new.split("\n")[-1])
if len(word) <= length:
if current_length + len(" ") + len(word) > length:
# If the new word would take the line's length over the maximum
# Add a new line and the word
new += "\n" + word
else:
if current_length != 0:
# to avoid adding a space at the start of the wrapped setence
# Add a space between words
new += " "
new += word # Add the word on to the end
else:
# if the length of the word is already longer than the maximum
# Break words into lines no more than (the maximum length - 1) chunks, and add a hyphen at the end
new_word = '\n'.join([word[i:i+length-1] + "-" for i in range(0,len(word),length-1)])
# Remove the final hyphen from the end
new_word = new_word[:-1]
# Add it onto the end
new += '\n' + new_word
print(new)
输出:
Lorem ipsum dolor sit amet, consectetur adipiscing
elit, sed do eiusmod tempor incididunt ut labore
et dolore magna aliqua. Ut enim ad minim veniam,
quis nostrud exercitation ullamco laboris nisi ut
aliquip ex ea commodo consequat. Duis aute irure
dolor in reprehenderit in voluptate velit esse
cillum dolore eu fugiat nulla pariatur. Excepteur
sint occaecat cupidatat non
proident,suntinculpaquiofficiadeseruntmollitanimi-
destlaborum.
推荐阅读
- python-3.x - 将 try/except 与 if/else 语句一起使用
- linux - 如何尾随 adb logcat 的输出并在每个新行中执行一个命令
- java - 将 lombok(或任何)注释添加到 swagger 生成的类
- c++ - 程序无法编译:将“int (*)[3][3]”分配给“int [9][3][3]”时的类型不兼容
- enums - 如何处理 flat_map 中的单个元素?
- swift - 如何将 UIPickerview selectRow 重置为默认零行
- testing - 为什么 Intellij 测试运行程序错误地计算测试?
- node.js - 如果评论没有自己的模型,我们如何删除用户的所有评论?
- python - 我想获取位于 div 中的标签内的多个 id 的值
- c++ - 从模块导出全局常量的正确方法是什么?