Python 3.x 在一个字符串中输入这么多字符后,找到最近的空格并将其放在新行上

Python 3.x 在一个字符串中输入这么多字符后,找到最近的空格并将其放在新行上,python-3.x,Python 3.x,我正试图使文件中的所有内容看起来整洁,但我遇到了一个问题。 我要求提供详细信息,如果长度超过27字节,则需要找到最近的前一个空格并将其放在新行上 (使用python 3.2) 我从以下几点开始: Details = input ("Details: ") delen = len(Details) if delen >27: #Code Here else: pass 这可能吗?如果是的话,你能帮我一下吗 干杯我不是Python专家。可能有一些奇特的方法可以做到这一点。我会

我正试图使文件中的所有内容看起来整洁,但我遇到了一个问题。 我要求提供
详细信息
,如果长度超过27字节,则需要找到最近的前一个空格并将其放在新行上

(使用python 3.2)

我从以下几点开始:

Details = input ("Details: ")
delen = len(Details)
if delen >27:
    #Code Here
else:
    pass
这可能吗?如果是的话,你能帮我一下吗


干杯

我不是Python专家。可能有一些奇特的方法可以做到这一点。我会保持简单,并做到:

Detail = input ("Details: ")
line_length = 27
delen = len(Detail)
pos = 0
while pos < delen:
    print Detail[pos:pos+line_length]
    pos += line_length
Detail=输入(“细节:”)
直线长度=27
delen=len(细节)
pos=0
而pos
我不是Python专家。可能有一些奇特的方法可以做到这一点。我会保持简单,并做到:

Detail = input ("Details: ")
line_length = 27
delen = len(Detail)
pos = 0
while pos < delen:
    print Detail[pos:pos+line_length]
    pos += line_length
Detail=输入(“细节:”)
直线长度=27
delen=len(细节)
pos=0
而pos是你的朋友

Details = input ("Details: ")
if len(Details) > 27:
    nearest_space = Details.rfind(' ', 0, 27)
    first, second = Details[:nearest_space], Details[nearest_space:]
else:
    first, second = Details, None
请注意,
rfind
如果在
详细信息
中找不到空格,将引发异常

Details = input ("Details: ")
if len(Details) > 27:
    nearest_space = Details.rfind(' ', 0, 27)
    first, second = Details[:nearest_space], Details[nearest_space:]
else:
    first, second = Details, None

请注意,
rfind
如果在
Details

中找不到空间,则会引发异常,该异常似乎工作得很好,谢谢。唯一的问题是细节字符串有时可能长达100个字符,因此需要拆分为两个以上的字符。请问还有什么办法吗?这似乎很有效,谢谢。唯一的问题是细节字符串有时可能长达100个字符,因此需要拆分为两个以上的字符。请问还有什么办法吗?