gpt4 book ai didi

python - 在用户输入的某些点切片和添加换行符的正确方法

转载 作者:太空宇宙 更新时间:2023-11-04 04:05:22 27 4
gpt4 key购买 nike

我有一个正在进行的程序,其中一个功能是获取用户提供的可能很长的字符串。但是,我需要确保字符串在某些点断开。我希望每行不超过 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 - 在用户输入的某些点切片和添加换行符的正确方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57450281/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com