Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cutting string after x chars at whitespace in python

Tags:

python

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?

like image 941
dynobo Avatar asked Sep 09 '13 07:09

dynobo


People also ask

How do you split a string after space in Python?

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.

How do you trim a string to a specific length in Python?

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].


2 Answers

import textwrap
lines = textwrap.wrap(text, 20)
# then use either
lines[0]
# or
'\n'.join(lines)
like image 53
Steve Barnes Avatar answered Sep 28 '22 06:09

Steve Barnes


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).

like image 45
Martijn Pieters Avatar answered Sep 28 '22 04:09

Martijn Pieters