Python Remove last 3 characters of a string

前端 未结 10 1314
-上瘾入骨i
-上瘾入骨i 2021-01-29 23:31

I\'m trying to remove the last 3 characters from a string in python, I don\'t know what these characters are so I can\'t use rstrip, I also need to remove any white

10条回答
  •  没有蜡笔的小新
    2021-01-30 00:24

    1. split
    2. slice
    3. concentrate

    This is a good workout for beginners and it's easy to achieve.

    Another advanced method is a function like this:

    def trim(s):
        return trim(s[slice])
    

    And for this question, you just want to remove the last characters, so you can write like this:

    def trim(s):
        return s[ : -3] 
    

    I think you are over to care about what those three characters are, so you lost. You just want to remove last three, nevertheless who they are!

    If you want to remove some specific characters, you can add some if judgements:

    def trim(s):
        if [conditions]:   ### for some cases, I recommend using isinstance().
            return trim(s[slice])
    

提交回复
热议问题