开发者

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 f开发者_JS百科or 'of' then strip everything off.


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


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'


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


p = find(v, "of")

gives you the position of "of" in v

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜