Python - How to cut a string in Python?

前端 未结 6 1506
失恋的感觉
失恋的感觉 2021-02-05 04:09

Suppose that I have the following string:

http://www.domain.com/?s=some&two=20

How can I take off what is after & includin

6条回答
  •  别那么骄傲
    2021-02-05 04:52

    You can use find()

    >>> s = 'http://www.domain.com/?s=some&two=20'
    >>> s[:s.find('&')]
    'http://www.domain.com/?s=some'
    

    Of course, if there is a chance that the searched for text will not be present then you need to write more lengthy code:

    pos = s.find('&')
    if pos != -1:
        s = s[:pos]
    

    Whilst you can make some progress using code like this, more complex situations demand a true URL parser.

提交回复
热议问题