Sunny
Sunny

Reputation: 7604

Stripping characters from a 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.

Upvotes: 2

Views: 296

Answers (4)

johnsyweb
johnsyweb

Reputation: 141780

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'

Upvotes: 4

ᅠᅠᅠ
ᅠᅠᅠ

Reputation: 66940

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

Upvotes: 7

unutbu
unutbu

Reputation: 879251

In [19]: v[v.rfind('of')+2:]
Out[19]: ' 5'

Upvotes: 0

Louis
Louis

Reputation: 2890

p = find(v, "of")

gives you the position of "of" in v

Upvotes: -1

Related Questions