Python Remove last 3 characters of a string












109















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?










share|improve this question





























    109















    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?










    share|improve this question



























      109












      109








      109


      13






      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?










      share|improve this question
















      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?







      python string






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Nov 25 '09 at 17:19









      abyx

      43.7k1578111




      43.7k1578111










      asked Nov 25 '09 at 17:14









      Sam MachinSam Machin

      1,19841017




      1,19841017
























          10 Answers
          10






          active

          oldest

          votes


















          199














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





          share|improve this answer



















          • 9





            I would like to note that ''.join(foo.split()) is better than foo.replace(' ', ''), when used on unicode strings because it removes any whitespace character, in addition to the ' ' character (in particular, non-breaking spaces are also removed). That said replace() is probably much faster, so it can be used if, say, the input strings are known to be encoded in ASCII, which only has one space character (I'm using Python 2 terminology, here.)

            – Eric O Lebigot
            Mar 14 '13 at 1:33





















          87














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



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





          share|improve this answer



















          • 11





            That doesn't remove WHITESPACE as the OP requested; it removes only SPACE characters.

            – John Machin
            Nov 26 '09 at 6:04



















          14














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





          share|improve this answer
























          • Is replace needed if strip already removes all whitespace?

            – Lidia
            Mar 31 '16 at 5:20






          • 2





            @Lidia Yes, strip only removes whitespace from the beginning and end of the string.

            – Eliezer Miron
            Sep 9 '16 at 20:31











          • It should be noted that you cannot chain this for example foo[3:]foo[:-3]

            – crafter
            Feb 4 '18 at 13:21



















          6














          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)






          share|improve this answer































            2














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



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






            share|improve this answer



















            • 1





              string.lower() should be string.upper(). My mistake.

              – krs1
              Nov 25 '09 at 17:34











            • this is the only solution that addresses whitespace well

              – Erik Aronesty
              May 14 '18 at 22:40



















            1














            What's wrong with this?



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





            share|improve this answer































              1














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





              share|improve this answer































                1
















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





                share|improve this answer

































                  0














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






                  share|improve this answer
























                  • points at the following in the question >>> (assuming no white space)

                    – Noctis Skytower
                    Nov 25 '09 at 17:32



















                  0














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





                  share|improve this answer























                    Your Answer






                    StackExchange.ifUsing("editor", function () {
                    StackExchange.using("externalEditor", function () {
                    StackExchange.using("snippets", function () {
                    StackExchange.snippets.init();
                    });
                    });
                    }, "code-snippets");

                    StackExchange.ready(function() {
                    var channelOptions = {
                    tags: "".split(" "),
                    id: "1"
                    };
                    initTagRenderer("".split(" "), "".split(" "), channelOptions);

                    StackExchange.using("externalEditor", function() {
                    // Have to fire editor after snippets, if snippets enabled
                    if (StackExchange.settings.snippets.snippetsEnabled) {
                    StackExchange.using("snippets", function() {
                    createEditor();
                    });
                    }
                    else {
                    createEditor();
                    }
                    });

                    function createEditor() {
                    StackExchange.prepareEditor({
                    heartbeatType: 'answer',
                    autoActivateHeartbeat: false,
                    convertImagesToLinks: true,
                    noModals: true,
                    showLowRepImageUploadWarning: true,
                    reputationToPostImages: 10,
                    bindNavPrevention: true,
                    postfix: "",
                    imageUploader: {
                    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
                    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
                    allowUrls: true
                    },
                    onDemand: true,
                    discardSelector: ".discard-answer"
                    ,immediatelyShowMarkdownHelp:true
                    });


                    }
                    });














                    draft saved

                    draft discarded


















                    StackExchange.ready(
                    function () {
                    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f1798465%2fpython-remove-last-3-characters-of-a-string%23new-answer', 'question_page');
                    }
                    );

                    Post as a guest















                    Required, but never shown

























                    10 Answers
                    10






                    active

                    oldest

                    votes








                    10 Answers
                    10






                    active

                    oldest

                    votes









                    active

                    oldest

                    votes






                    active

                    oldest

                    votes









                    199














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





                    share|improve this answer



















                    • 9





                      I would like to note that ''.join(foo.split()) is better than foo.replace(' ', ''), when used on unicode strings because it removes any whitespace character, in addition to the ' ' character (in particular, non-breaking spaces are also removed). That said replace() is probably much faster, so it can be used if, say, the input strings are known to be encoded in ASCII, which only has one space character (I'm using Python 2 terminology, here.)

                      – Eric O Lebigot
                      Mar 14 '13 at 1:33


















                    199














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





                    share|improve this answer



















                    • 9





                      I would like to note that ''.join(foo.split()) is better than foo.replace(' ', ''), when used on unicode strings because it removes any whitespace character, in addition to the ' ' character (in particular, non-breaking spaces are also removed). That said replace() is probably much faster, so it can be used if, say, the input strings are known to be encoded in ASCII, which only has one space character (I'm using Python 2 terminology, here.)

                      – Eric O Lebigot
                      Mar 14 '13 at 1:33
















                    199












                    199








                    199







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





                    share|improve this answer













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






                    share|improve this answer












                    share|improve this answer



                    share|improve this answer










                    answered Nov 25 '09 at 17:23









                    Noctis SkytowerNoctis Skytower

                    14k126090




                    14k126090








                    • 9





                      I would like to note that ''.join(foo.split()) is better than foo.replace(' ', ''), when used on unicode strings because it removes any whitespace character, in addition to the ' ' character (in particular, non-breaking spaces are also removed). That said replace() is probably much faster, so it can be used if, say, the input strings are known to be encoded in ASCII, which only has one space character (I'm using Python 2 terminology, here.)

                      – Eric O Lebigot
                      Mar 14 '13 at 1:33
















                    • 9





                      I would like to note that ''.join(foo.split()) is better than foo.replace(' ', ''), when used on unicode strings because it removes any whitespace character, in addition to the ' ' character (in particular, non-breaking spaces are also removed). That said replace() is probably much faster, so it can be used if, say, the input strings are known to be encoded in ASCII, which only has one space character (I'm using Python 2 terminology, here.)

                      – Eric O Lebigot
                      Mar 14 '13 at 1:33










                    9




                    9





                    I would like to note that ''.join(foo.split()) is better than foo.replace(' ', ''), when used on unicode strings because it removes any whitespace character, in addition to the ' ' character (in particular, non-breaking spaces are also removed). That said replace() is probably much faster, so it can be used if, say, the input strings are known to be encoded in ASCII, which only has one space character (I'm using Python 2 terminology, here.)

                    – Eric O Lebigot
                    Mar 14 '13 at 1:33







                    I would like to note that ''.join(foo.split()) is better than foo.replace(' ', ''), when used on unicode strings because it removes any whitespace character, in addition to the ' ' character (in particular, non-breaking spaces are also removed). That said replace() is probably much faster, so it can be used if, say, the input strings are known to be encoded in ASCII, which only has one space character (I'm using Python 2 terminology, here.)

                    – Eric O Lebigot
                    Mar 14 '13 at 1:33















                    87














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



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





                    share|improve this answer



















                    • 11





                      That doesn't remove WHITESPACE as the OP requested; it removes only SPACE characters.

                      – John Machin
                      Nov 26 '09 at 6:04
















                    87














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



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





                    share|improve this answer



















                    • 11





                      That doesn't remove WHITESPACE as the OP requested; it removes only SPACE characters.

                      – John Machin
                      Nov 26 '09 at 6:04














                    87












                    87








                    87







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



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





                    share|improve this answer













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



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






                    share|improve this answer












                    share|improve this answer



                    share|improve this answer










                    answered Nov 25 '09 at 17:17









                    Nadia AlramliNadia Alramli

                    80.1k25153147




                    80.1k25153147








                    • 11





                      That doesn't remove WHITESPACE as the OP requested; it removes only SPACE characters.

                      – John Machin
                      Nov 26 '09 at 6:04














                    • 11





                      That doesn't remove WHITESPACE as the OP requested; it removes only SPACE characters.

                      – John Machin
                      Nov 26 '09 at 6:04








                    11




                    11





                    That doesn't remove WHITESPACE as the OP requested; it removes only SPACE characters.

                    – John Machin
                    Nov 26 '09 at 6:04





                    That doesn't remove WHITESPACE as the OP requested; it removes only SPACE characters.

                    – John Machin
                    Nov 26 '09 at 6:04











                    14














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





                    share|improve this answer
























                    • Is replace needed if strip already removes all whitespace?

                      – Lidia
                      Mar 31 '16 at 5:20






                    • 2





                      @Lidia Yes, strip only removes whitespace from the beginning and end of the string.

                      – Eliezer Miron
                      Sep 9 '16 at 20:31











                    • It should be noted that you cannot chain this for example foo[3:]foo[:-3]

                      – crafter
                      Feb 4 '18 at 13:21
















                    14














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





                    share|improve this answer
























                    • Is replace needed if strip already removes all whitespace?

                      – Lidia
                      Mar 31 '16 at 5:20






                    • 2





                      @Lidia Yes, strip only removes whitespace from the beginning and end of the string.

                      – Eliezer Miron
                      Sep 9 '16 at 20:31











                    • It should be noted that you cannot chain this for example foo[3:]foo[:-3]

                      – crafter
                      Feb 4 '18 at 13:21














                    14












                    14








                    14







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





                    share|improve this answer













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






                    share|improve this answer












                    share|improve this answer



                    share|improve this answer










                    answered Nov 26 '09 at 1:15









                    ghostdog74ghostdog74

                    222k42212303




                    222k42212303













                    • Is replace needed if strip already removes all whitespace?

                      – Lidia
                      Mar 31 '16 at 5:20






                    • 2





                      @Lidia Yes, strip only removes whitespace from the beginning and end of the string.

                      – Eliezer Miron
                      Sep 9 '16 at 20:31











                    • It should be noted that you cannot chain this for example foo[3:]foo[:-3]

                      – crafter
                      Feb 4 '18 at 13:21



















                    • Is replace needed if strip already removes all whitespace?

                      – Lidia
                      Mar 31 '16 at 5:20






                    • 2





                      @Lidia Yes, strip only removes whitespace from the beginning and end of the string.

                      – Eliezer Miron
                      Sep 9 '16 at 20:31











                    • It should be noted that you cannot chain this for example foo[3:]foo[:-3]

                      – crafter
                      Feb 4 '18 at 13:21

















                    Is replace needed if strip already removes all whitespace?

                    – Lidia
                    Mar 31 '16 at 5:20





                    Is replace needed if strip already removes all whitespace?

                    – Lidia
                    Mar 31 '16 at 5:20




                    2




                    2





                    @Lidia Yes, strip only removes whitespace from the beginning and end of the string.

                    – Eliezer Miron
                    Sep 9 '16 at 20:31





                    @Lidia Yes, strip only removes whitespace from the beginning and end of the string.

                    – Eliezer Miron
                    Sep 9 '16 at 20:31













                    It should be noted that you cannot chain this for example foo[3:]foo[:-3]

                    – crafter
                    Feb 4 '18 at 13:21





                    It should be noted that you cannot chain this for example foo[3:]foo[:-3]

                    – crafter
                    Feb 4 '18 at 13:21











                    6














                    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)






                    share|improve this answer




























                      6














                      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)






                      share|improve this answer


























                        6












                        6








                        6







                        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)






                        share|improve this answer













                        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)







                        share|improve this answer












                        share|improve this answer



                        share|improve this answer










                        answered Nov 25 '09 at 17:22









                        Mattias NilssonMattias Nilsson

                        2,97311526




                        2,97311526























                            2














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



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






                            share|improve this answer



















                            • 1





                              string.lower() should be string.upper(). My mistake.

                              – krs1
                              Nov 25 '09 at 17:34











                            • this is the only solution that addresses whitespace well

                              – Erik Aronesty
                              May 14 '18 at 22:40
















                            2














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



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






                            share|improve this answer



















                            • 1





                              string.lower() should be string.upper(). My mistake.

                              – krs1
                              Nov 25 '09 at 17:34











                            • this is the only solution that addresses whitespace well

                              – Erik Aronesty
                              May 14 '18 at 22:40














                            2












                            2








                            2







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



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






                            share|improve this answer













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



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







                            share|improve this answer












                            share|improve this answer



                            share|improve this answer










                            answered Nov 25 '09 at 17:29









                            krs1krs1

                            944515




                            944515








                            • 1





                              string.lower() should be string.upper(). My mistake.

                              – krs1
                              Nov 25 '09 at 17:34











                            • this is the only solution that addresses whitespace well

                              – Erik Aronesty
                              May 14 '18 at 22:40














                            • 1





                              string.lower() should be string.upper(). My mistake.

                              – krs1
                              Nov 25 '09 at 17:34











                            • this is the only solution that addresses whitespace well

                              – Erik Aronesty
                              May 14 '18 at 22:40








                            1




                            1





                            string.lower() should be string.upper(). My mistake.

                            – krs1
                            Nov 25 '09 at 17:34





                            string.lower() should be string.upper(). My mistake.

                            – krs1
                            Nov 25 '09 at 17:34













                            this is the only solution that addresses whitespace well

                            – Erik Aronesty
                            May 14 '18 at 22:40





                            this is the only solution that addresses whitespace well

                            – Erik Aronesty
                            May 14 '18 at 22:40











                            1














                            What's wrong with this?



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





                            share|improve this answer




























                              1














                              What's wrong with this?



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





                              share|improve this answer


























                                1












                                1








                                1







                                What's wrong with this?



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





                                share|improve this answer













                                What's wrong with this?



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






                                share|improve this answer












                                share|improve this answer



                                share|improve this answer










                                answered Nov 25 '09 at 17:18









                                abyxabyx

                                43.7k1578111




                                43.7k1578111























                                    1














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





                                    share|improve this answer




























                                      1














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





                                      share|improve this answer


























                                        1












                                        1








                                        1







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





                                        share|improve this answer













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






                                        share|improve this answer












                                        share|improve this answer



                                        share|improve this answer










                                        answered Nov 25 '09 at 17:18









                                        SilentGhostSilentGhost

                                        197k47268264




                                        197k47268264























                                            1
















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





                                            share|improve this answer






























                                              1
















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





                                              share|improve this answer




























                                                1












                                                1








                                                1









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





                                                share|improve this answer

















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






                                                share|improve this answer














                                                share|improve this answer



                                                share|improve this answer








                                                edited Nov 29 '18 at 6:15

























                                                answered Nov 28 '18 at 1:50









                                                JaylinJaylin

                                                163




                                                163























                                                    0














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






                                                    share|improve this answer
























                                                    • points at the following in the question >>> (assuming no white space)

                                                      – Noctis Skytower
                                                      Nov 25 '09 at 17:32
















                                                    0














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






                                                    share|improve this answer
























                                                    • points at the following in the question >>> (assuming no white space)

                                                      – Noctis Skytower
                                                      Nov 25 '09 at 17:32














                                                    0












                                                    0








                                                    0







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






                                                    share|improve this answer













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







                                                    share|improve this answer












                                                    share|improve this answer



                                                    share|improve this answer










                                                    answered Nov 25 '09 at 17:26









                                                    AndreaGAndreaG

                                                    7902925




                                                    7902925













                                                    • points at the following in the question >>> (assuming no white space)

                                                      – Noctis Skytower
                                                      Nov 25 '09 at 17:32



















                                                    • points at the following in the question >>> (assuming no white space)

                                                      – Noctis Skytower
                                                      Nov 25 '09 at 17:32

















                                                    points at the following in the question >>> (assuming no white space)

                                                    – Noctis Skytower
                                                    Nov 25 '09 at 17:32





                                                    points at the following in the question >>> (assuming no white space)

                                                    – Noctis Skytower
                                                    Nov 25 '09 at 17:32











                                                    0














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





                                                    share|improve this answer




























                                                      0














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





                                                      share|improve this answer


























                                                        0












                                                        0








                                                        0







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





                                                        share|improve this answer













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






                                                        share|improve this answer












                                                        share|improve this answer



                                                        share|improve this answer










                                                        answered Nov 25 '09 at 17:33









                                                        Lee JoramoLee Joramo

                                                        465




                                                        465






























                                                            draft saved

                                                            draft discarded




















































                                                            Thanks for contributing an answer to Stack Overflow!


                                                            • Please be sure to answer the question. Provide details and share your research!

                                                            But avoid



                                                            • Asking for help, clarification, or responding to other answers.

                                                            • Making statements based on opinion; back them up with references or personal experience.


                                                            To learn more, see our tips on writing great answers.




                                                            draft saved


                                                            draft discarded














                                                            StackExchange.ready(
                                                            function () {
                                                            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f1798465%2fpython-remove-last-3-characters-of-a-string%23new-answer', 'question_page');
                                                            }
                                                            );

                                                            Post as a guest















                                                            Required, but never shown





















































                                                            Required, but never shown














                                                            Required, but never shown












                                                            Required, but never shown







                                                            Required, but never shown

































                                                            Required, but never shown














                                                            Required, but never shown












                                                            Required, but never shown







                                                            Required, but never shown







                                                            Popular posts from this blog

                                                            Lallio

                                                            Unable to find Lightning Node

                                                            Futebolista