Reputation: 10182
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!
Upvotes: 1
Views: 3234
Reputation: 1146
Just to improve on your final solution: you can use string.find(' ', n)
to find the index of the first space after character n. If you want to split after that space (so that string1 ends with a space, rather than string2 beginning with one), just add one to it:
>>> 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
Upvotes: 2
Reputation: 1121296
You are looking for slicing:
MyText1, MyText2 = MyText[:max_char], MyText[max_char:]
Python strings are sequences, to select the first max_char
characters, simply use a slice to select those, and for the second half select everything starting at max_char
until the end.
This is covered in the Python tutorial as well.
Upvotes: 5