如果这是一个重复的,我很抱歉,但我似乎找不到任何涉及到基于字符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 = ''
现在,我确信有一种更有效/更优雅的方法来做这件事,但这仍然有效,所以希望有人能从中受益。谢谢!在
您正在寻找slicing:
Python字符串是序列,要选择前一个
max_char
字符,只需使用一个片段来选择这些字符,对于后半部分,选择从max_char
开始直到结尾的所有字符。在这也是covered in the Python tutorial。在
为了改进您的最终解决方案:您可以使用
string.find(' ', n)
来查找字符n后第一个空格的索引。如果要在该空格后拆分(使string1以空格结尾,而不是string2以1开头),只需在其中添加一个:相关问题 更多 >
编程相关推荐