Python Remove last 3 characters of a string

前端 未结 10 1196
-上瘾入骨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:13

    It some what depends on your definition of whitespace. I would generally call whitespace to be spaces, tabs, line breaks and carriage returns. If this is your definition you want to use a regex with \s to replace all whitespace charactors:

    import re
    
    def myCleaner(foo):
        print 'dirty: ', foo
        foo = re.sub(r'\s', '', foo)
        foo = foo[:-3]
        foo = foo.upper()
        print 'clean:', foo
        print
    
    myCleaner("BS1 1AB")
    myCleaner("bs11ab")
    myCleaner("BS111ab")
    
    0 讨论(0)
  • 2021-01-30 00:16
    >>> foo = "Bs12 3ab"
    >>> foo[:-3]
    'Bs12 '
    >>> foo[:-3].strip()
    'Bs12'
    >>> foo[:-3].strip().replace(" ","")
    'Bs12'
    >>> foo[:-3].strip().replace(" ","").upper()
    'BS12'
    
    0 讨论(0)
  • 2021-01-30 00:18

    Removing any and all whitespace:

    foo = ''.join(foo.split())
    

    Removing last three characters:

    foo = foo[:-3]
    

    Converting to capital letters:

    foo = foo.upper()
    

    All of that code in one line:

    foo = ''.join(foo.split())[:-3].upper()
    
    0 讨论(0)
  • 2021-01-30 00:19

    What's wrong with this?

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

    You might have misunderstood rstrip slightly, it strips not a string but any character in the string you specify.

    Like this:

    >>> text = "xxxxcbaabc"
    >>> text.rstrip("abc")
    'xxxx'
    

    So instead, just use

    text = text[:-3] 
    

    (after replacing whitespace with nothing)

    0 讨论(0)
  • 2021-01-30 00:22
    >>> foo = 'BS1 1AB'
    >>> foo.replace(" ", "").rstrip()[:-3].upper()
    'BS1'
    
    0 讨论(0)
提交回复
热议问题