Python strip a string at a certain spot

This question already has an answer here:

  • Is there a way to substring a string in Python? 10 answers

  • You can do this using Python's slice notation:

    >>> mystr = 'foo7bar'
    >>> mystr[:mystr.index('7')]
    'foo'
    >>>
    

    The format for slice notation is [start:stop:step] . The index method of a string finds the position of the first occurrence of its input.

    Note however that if you are dealing with something more complex (such as matching patterns), you might want to look into Regular Expressions. For this operation though, the slice notation is sufficient.

    链接地址: http://www.djcxy.com/p/55118.html

    上一篇: 从字符串中删除“x”个字符?

    下一篇: Python在特定位置剥离一个字符串