I want to cut a long text after x characters, but I don't want to cut a word in the middle, I want to cut at the last whitespace before x chars:
'This is a sample text'[:20]
gives me
'This is a sample tex'
but I want
'This is a sample'
Another example:
'And another sample sentence'[:15]
gives me
'And another sam'
but I want
'And another'
What is the easiest way to do this?
The split() method splits a string into a list. You can specify the separator, default separator is any whitespace. Note: When maxsplit is specified, the list will contain the specified number of elements plus one.
Use syntax string[x:y] to slice a string starting from index x up to but not including the character at index y. If you want only to cut the string to length in python use only string[: length].
import textwrap
lines = textwrap.wrap(text, 20)
# then use either
lines[0]
# or
'\n'.join(lines)
You can use str.rpartition()
or str.rsplit()
to remove everything after the last space of the remainder:
example[:20].rpartition(' ')[0]
example[:20].rsplit(' ', 1)[0]
The second argument to str.rsplit()
limits the split to the first space from the right, and the [0]
index takes whatever was split off before that space.
str.rpartition()
is a bit faster, and always returns three strings; if there was no space then the first string returned is empty, so you may want to stick with str.rsplit()
if that’s a possibility (that version would return a list with a single string in that case, so you end up with the original string again).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With