Ways to slice a string?

后端 未结 6 650
渐次进展
渐次进展 2020-12-01 21:16

I have a string, example:

s = \"this is a string, a\"

Where a \',\' (comma) will always be the 3rd to the last character, aka

6条回答
  •  星月不相逢
    2020-12-01 22:05

    A couple of variants, using the "delete the last comma" rather than "delete third last character" are:

    s[::-1].replace(",","",1)[::-1]
    

    or

    ''.join(s.rsplit(",", 1))
    

    But these are pretty ugly. Slightly better is:

    a, _, b = s.rpartition(",")
    s = a + b
    

    This may be the best approach if you don't know the comma's position (except for last comma in string) and effectively need a "replace from right". However Anurag's answer is more pythonic for the "delete third last character".

提交回复
热议问题