在Python中,如何在特定的字符数之后拆分字符串?

2024-09-29 02:21:11 发布

您现在位置:Python中文网/ 问答频道 /正文

如果这是一个重复的,我很抱歉,但我似乎找不到任何涉及到基于字符count拆分字符串的内容。例如,假设我有以下字符串:

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed ullamcorper, eros 
sed porta dapibus, nunc nibh iaculis tortor, in rhoncus quam orci sed ante. Sed 
ac dictum nibh.

现在,我可以根据一个特定的字符分割字符串,但是如何在nth字符之后分割这个字符串,而不管它是什么?像这样,只有使用一个有效的语法,我在想:

^{pr2}$

任何帮助都将不胜感激。谢谢!在

更新

我想发布这个更新,因为我的问题只解决了我问题的一半。多亏了马蒂金下面的回答,我很容易就把上面的绳子剪断了。但是,由于我编辑的字符串是用户提交的,所以我遇到了将单词切成两半的问题。为了解决这个问题,我使用了rsplit和{}的组合来正确地分解段落。万一有人和我面临同样的问题,这里是我用来让它工作的代码:

line1 = note[:36]
line2 = note[36:]

if not line1.endswith(' ', 1):
 line2_2 = line1.rsplit(' ')[-1]
 line1_1 = line1.rstrip(line2_2)
 line2_2 = line2_2 + line2
 line1 = ''
 line2 = ''

现在,我确信有一种更有效/更优雅的方法来做这件事,但这仍然有效,所以希望有人能从中受益。谢谢!在


Tags: 字符串内容count字符sednoteipsumlorem
2条回答

您正在寻找slicing

MyText1, MyText2 = MyText[:max_char], MyText[max_char:]

Python字符串是序列,要选择前一个max_char字符,只需使用一个片段来选择这些字符,对于后半部分,选择从max_char开始直到结尾的所有字符。在

这也是covered in the Python tutorial。在

为了改进您的最终解决方案:您可以使用string.find(' ', n)来查找字符n后第一个空格的索引。如果要在该空格后拆分(使string1以空格结尾,而不是string2以1开头),只需在其中添加一个:

>>> print string
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed ullamcorper, eros sed porta dapibus, nunc nibh iaculis tortor, in rhoncus quam orci sed ante. Sed
>>> space_location = string.find(' ', 36)+1
>>> print string[:space_location]
Lorem ipsum dolor sit amet, consectetur 
>>> print string[space_location:]
adipiscing elit. Sed ullamcorper, eros sed porta dapibus, nunc nibh iaculis tortor, in rhoncus quam orci sed ante. Sed

相关问题 更多 >