Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Stripping characters from a Python string

Tags:

python

string

I have a string:

v = "1 - 5 of 5"

I would like only the part after 'of' (5 in the above) and strip everything before 'of', including 'of'?

The problem is that the string is not fixed as in it could be '1-100 of 100', so I can't specify to strip everything off after the 10 or so characters. I need to search for 'of' then strip everything off.

like image 859
Sunny Avatar asked May 08 '26 21:05

Sunny


2 Answers

Using the partition method is most readable for these cases.

string = "1 - 5 of 5"
first_part, middle, last_part = string.partition('of')

result = last_part.strip()
like image 85
Petr Viktorin Avatar answered May 11 '26 10:05

Petr Viktorin


str.partition() was built for exactly this kind of problem:

In [2]: v = "1 - 5 of 5"

In [3]: v.partition('of')
Out[3]: ('1 - 5 ', 'of', ' 5')

In [4]: v.partition('of')[-1]
Out[4]: ' 5'
like image 26
Johnsyweb Avatar answered May 11 '26 09:05

Johnsyweb



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!