问题:Python删除字符串的最后3个字符

我正在尝试从python的字符串中删除最后3个字符,我不知道这些字符是什么,所以我无法使用rstrip,我还需要删除任何空格并将其转换为大写

一个例子是:

foo = "Bs12 3ab"
foo.replace(" ", "").rstrip(foo[-3:]).upper()

这可以使我得到我想要的BS12,但是如果最后第4个和第3个字符相同,我会同时松开两个,例如,如果foo = "BS11 1AA"我刚得到'BS'

的示例foo可能是:

BS1 1AB
bs11ab
BS111ab

该字符串可以是6或7个字符,我需要删除最后3个字符(假设没有空格)

有小费吗?

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 space and convert to upper-case

an example would be:

foo = "Bs12 3ab"
foo.replace(" ", "").rstrip(foo[-3:]).upper()

This works and gives me BS12 which is what I want, however if the last 4th & 3rd characters are the same I loose both eg if foo = "BS11 1AA" I just get 'BS'

examples of foo could be:

BS1 1AB
bs11ab
BS111ab

The string could be 6 or 7 characters and I need to drop the last 3 (assuming no white space)

Any tips?


回答 0

删除所有空格:

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

删除最后三个字符:

foo = foo[:-3]

转换为大写字母:

foo = foo.upper()

所有这些代码都在一行中:

foo = ''.join(foo.split())[:-3].upper()

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()

回答 1

它不按预期工作,因为strip是基于字符的。您需要执行以下操作:

foo = foo.replace(' ', '')[:-3].upper()

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

foo = foo.replace(' ', '')[:-3].upper()

回答 2

>>> foo = "Bs12 3ab"
>>> foo[:-3]
'Bs12 '
>>> foo[:-3].strip()
'Bs12'
>>> foo[:-3].strip().replace(" ","")
'Bs12'
>>> foo[:-3].strip().replace(" ","").upper()
'BS12'
>>> foo = "Bs12 3ab"
>>> foo[:-3]
'Bs12 '
>>> foo[:-3].strip()
'Bs12'
>>> foo[:-3].strip().replace(" ","")
'Bs12'
>>> foo[:-3].strip().replace(" ","").upper()
'BS12'

回答 3

您可能对rstrip略有误解,它不会去除字符串,而是去除您指定的字符串中的任何字符。

像这样:

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

因此,只需使用

text = text[:-3] 

(用空白替换空白后)

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)


回答 4

>>> foo = 'BS1 1AB'
>>> foo.replace(" ", "").rstrip()[:-3].upper()
'BS1'
>>> foo = 'BS1 1AB'
>>> foo.replace(" ", "").rstrip()[:-3].upper()
'BS1'

回答 5

我尝试避免使用正则表达式,但这似乎可行:

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

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

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


回答 6

这怎么了

foo.replace(" ", "")[:-3].upper()

What’s wrong with this?

foo.replace(" ", "")[:-3].upper()

回答 7

  1. split
  2. slice
  3. concentrate

对于初学者来说这是一个很好的锻炼,很容易实现。

另一个高级方法是这样的函数:

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

对于这个问题,您只想删除最后符,因此可以这样写:

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

我认为您已经在乎这三个字符是什么,所以您迷路了。您只想删除最后三个,但它们是谁!

如果要删除某些特定字符,则可以添加一些判断:

def trim(s):
    if [conditions]:   ### for some cases, I recommend using isinstance().
        return trim(s[slice])
  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])

回答 8

您不是以错误的顺序执行操作吗?您的要求似乎是foo[:-3].replace(" ", "").upper()

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


回答 9

这取决于您对空格的定义。我通常将空白称为空格,制表符,换行符和回车符。如果这是您的定义,则要使用带有\ s的正则表达式来替换所有空白字符:

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")

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")

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。