I apologize if this is a duplicate but I can't seem to find anything out there that involves splitting a string based on a character count. For example, let's say I have the following 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
ac dictum nibh.
Now, I can split the string based on a specific character, but how can I split this string after the nth character, regardless of what it is? Something like this, only with a working syntax is what I am thinking:
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
Any help would be appreciated. Thanks!
Update
I wanted to post this update since my question only approached half of my problem. Thanks to Martijin's answer below I easily sliced the string above. However, since the string I was making edits to was user submitted, I ran into the problem of slicing words in half. In order to fix this problem, I used a combination of rsplit
and rstrip
to break up the paragraph correctly. Just in case someone out there is facing the same issues as me here is the code I used to make it work:
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 = ''
Now, I'm sure there is a more efficient/elegant way of doing this, but this still works so hopefully somebody can benefit from it. Thanks!