Python Remove last 3 characters of a string

前端 未结 10 1161
-上瘾入骨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])
    
    0 讨论(0)
  • 2021-01-30 00:26

    Aren't you performing the operations in the wrong order? You requirement seems to be foo[:-3].replace(" ", "").upper()

    0 讨论(0)
  • 2021-01-30 00:31

    It doesn't work as you expect because strip is character based. You need to do this instead:

    foo = foo.replace(' ', '')[:-3].upper()
    
    0 讨论(0)
  • 2021-01-30 00:36

    I try to avoid regular expressions, but this appears to work:

    string = re.sub("\s","",(string.lower()))[:-3]

    0 讨论(0)
提交回复
热议问题