Dot notation string manipulation

前端 未结 5 1151
伪装坚强ぢ
伪装坚强ぢ 2020-12-07 00:28

Is there a way to manipulate a string in Python using the following ways?

For any string that is stored in dot notation, for example:

s = \"classes.s         


        
5条回答
  •  悲&欢浪女
    2020-12-07 01:27

    If your goal is to get rid of a final component that's just a single digit, start and end with re.sub():

    s = re.sub(r"\.\d$", "", s)
    

    This will do the job, and leave other strings alone. No need to mess with anything else.

    If you do want to know about the general case (separate out the last component, no matter what it is), then use rsplit to split your string once:

    >>> "hel.lo.there".rsplit(".", 1)
    ['hel.lo', 'there']
    

    If there's no dot in the string you'll just get one element in your array, the entire string.

提交回复
热议问题