omz:forum

    • Register
    • Login
    • Search
    • Recent
    • Popular

    Welcome!

    This is the community forum for my apps Pythonista and Editorial.

    For individual support questions, you can also send an email. If you have a very short question or just want to say hello — I'm @olemoritz on Twitter.


    Function at end of variable (Don't really know how to sum up this question)

    Pythonista
    6
    9
    3987
    Loading More Posts
    • Oldest to Newest
    • Newest to Oldest
    • Most Votes
    Reply
    • Reply as topic
    Log in to reply
    This topic has been deleted. Only users with topic management privileges can see it.
    • Drizzel
      Drizzel last edited by

      Hi,
      so I have this function:

      def clean(data):
           while data.startswith(' '): data = data[1:]
           while data.endswith(' '): data = data[:-1]
           return data
      

      Therefore clean(" random string ") returns "random string" . Is it possible to get the same result with " random string ".clean() ?
      After all "random string".lower() is possible too.

      cvp 1 Reply Last reply Reply Quote 0
      • cvp
        cvp @Drizzel last edited by

        @Drizzel is that not the strip function?

        1 Reply Last reply Reply Quote 0
        • Drizzel
          Drizzel last edited by Drizzel

          @cvp True, forgot about that :)
          Nevertheless, is it possible to do this in general?

          cvp mikael 2 Replies Last reply Reply Quote 0
          • cvp
            cvp @Drizzel last edited by

            @Drizzel Sorry for that, but I can't answer. I'm sincerely not very good in Python it-self.
            Sure that @ccc or @mikael could answer

            1 Reply Last reply Reply Quote 0
            • pulbrich
              pulbrich last edited by pulbrich

              You can subclass str and insert your method in the subclass definition. As long as you use your subclass to create your “string” instances the new method would work. Not for literals though. E.g.,

              class funny_string(str):
                def clean(data):
                   while data.startswith(' '): data = data[1:]
                   while data.endswith(' '): data = data[:-1]
                   return data
              
              my_string = funny_string(“ look at this! “)
              print(my_string.clean()) #### works
              print(“ huh? “.clean()) #### doesn’t work
              
              mikael 1 Reply Last reply Reply Quote 1
              • mikael
                mikael @Drizzel last edited by mikael

                @Drizzel, well, sort of, see below. But not really, since you cannot modify the built-in class (str.a = 'a' results in an error).

                from collections import UserString
                
                
                class Cleanable(UserString):
                    
                    def clean(self):
                        return self.strip()
                        
                        
                mystr = Cleanable(' random string ')
                
                assert 'string' in mystr
                assert mystr.clean() == 'random string'
                
                1 Reply Last reply Reply Quote 0
                • mikael
                  mikael @pulbrich last edited by mikael

                  @pulbrich, heh. @Drizzel, @pulbrich’s version is better, UserString is a throwback to very old Python 2.

                  1 Reply Last reply Reply Quote 1
                  • Zoot
                    Zoot last edited by ccc

                    @Drizzel said:

                    def clean(data):
                    while data.startswith(' '): data = data[1:]
                    while data.endswith(' '): data = data[:-1]
                    return data

                    Just for fun, a couple comments on this function. As written I think it's going to be safe in all cases, but a subtle point is that if the passed in object starts or ends with a space then a new object is returned, but if neither case is true it returns the original object. Since stings are immutable this won't cause a problem, and the startswith() method will fail if you try to pass it a bytes or bytearray object, but if you had written it slightly differently:

                    def clean(data):
                         while data[0] == ' ': data = data[1:]
                         while data[-1] == ' ': data = data[:-1]
                         return data
                    

                    Then the function would work with something like:

                    mylist = list('Hello World')
                    stripped_list = clean(mylist)
                    

                    and since lists are mutable, whether or not you return the same object could affect the program behavior if other references are kept to the original mylist, since changing stripped_list will either also affect mylist or not depending on whether it had leading or trailing elements that were a space.

                    1 Reply Last reply Reply Quote 0
                    • Olaf
                      Olaf @Guest last edited by

                      @JITASIDA
                      No, you can't
                      That would require adding a method to a built-in type and that's not possible (without going to the C source for Python):

                      >>> str.clean=lambda self:'clean'+self
                      Traceback (most recent call last):
                        File "<string>", line 1, in <module>
                      TypeError: can't set attributes of built-in/extension type 'str'
                      
                      1 Reply Last reply Reply Quote 0
                      • First post
                        Last post
                      Powered by NodeBB Forums | Contributors