如何在Python中按特定字符数拆分字符串?

1 投票
2 回答
3195 浏览
提问于 2025-04-17 15:47

抱歉如果这个问题重复了,但我找不到任何关于根据字符数量来分割字符串的内容。比如说,我有以下这个字符串:

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 个字符后分割这个字符串,而不管它是什么字符?我想的就是像这样,只不过语法要能正常工作:

max_char = n #where n is the number of characters to split after
MyText = 'User input string. This is usually at least a paragraph long.'
char_count = len(MyText)
if char_count > max_char:
 #split string at max_char, create variables: MyText1 and MyText2

任何帮助都非常感谢。谢谢!

更新

我想发布这个更新,因为我的问题只解决了一半。感谢Martijin的回答,我轻松地分割了上面的字符串。不过,由于我处理的字符串是用户提交的,我遇到了把单词切成两半的问题。为了解决这个问题,我结合使用了rsplitrstrip来正确地分割段落。为了帮助那些和我有相同问题的人,这里是我用来让它工作的代码:

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 = ''

现在,我相信还有更有效或更优雅的方法来做到这一点,但这个方法仍然有效,希望能对某些人有所帮助。谢谢!

2 个回答

2

为了让你的最终解决方案更好,你可以使用 string.find(' ', n) 来找到字符 n 后面第一个空格的位置。如果你想在那个空格后面进行分割(这样 string1 结尾是空格,而不是 string2 开头是空格),只需要在这个位置上加一:

>>> 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
5

你在寻找切片的用法:

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

在Python中,字符串是一个序列。如果你想选取前面max_char个字符,可以简单地使用切片来选择这些字符。对于后半部分,你可以从max_char开始,选择一直到字符串的结尾。

这个内容在Python教程中也有介绍。

撰写回答