簡體   English   中英

特定字符數后,如何在Python中分割字符串?

[英]How can I split a string in Python after a specific character 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.

現在,我可以根據特定字符分割字符串,但是無論如何,如何在第n 字符之后分割此字符串? 像這樣,只有在使用有效語法的情況下,我的想法是:

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

現在,我敢肯定有一種更有效/更優雅的方法可以做到這一點,但這仍然奏效,希望有人可以從中受益。 謝謝!

您正在尋找切片

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

Python字符串是序列,要選擇第一個max_char字符,只需使用一個切片將其選中,然后對后半部分選擇從max_char開始直到結尾的所有max_char

Python教程中也對此進行了介紹

只是為了改善最終解決方案:您可以使用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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM