why is python string split() not splitting

I have the following python code.

class MainPage(BaseHandler):

    def post(self, location_id):
        reservations = self.request.get_all('reservations')
        for r in reservations:
            a=str(r)
            logging.info("r: %s " % r)
            logging.info("lenr: %s " % len(r))
            logging.info("a: %s " % a)
            logging.info("lena: %s " % len(a))
            r.split(' ')
            a.split(' ')
            logging.info("split r: %s " % r)
            logging.info("split a: %s " % a)

I get the following log printout.

INFO     2012-09-02 17:58:51,605 views.py:98] r: court2 13 0 2012 9 2 
INFO     2012-09-02 17:58:51,605 views.py:99] lenr: 20 
INFO     2012-09-02 17:58:51,605 views.py:100] a: court2 13 0 2012 9 2 
INFO     2012-09-02 17:58:51,606 views.py:101] lena: 20 
INFO     2012-09-02 17:58:51,606 views.py:108] split r: court2 13 0 2012 9 2 
INFO     2012-09-02 17:58:51,606 views.py:109] split a: court2 13 0 2012 9 2

I get the same log printout if instead of split(‘ ‘) I use split(), btw.

Why is split not splitting the result into a list with 6 entries? I suppose the problem is that http request is involved, because my tests in the gae interactive console get the expected result.

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

split does not modify the string. It returns a list of the split pieces. If you want to use that list, you need to assign it to something with, e.g., r = r.split(' ').

Method 2

split does not split the original string, but returns a list

>>> r  = 'court2 13 0 2012 9 2'
>>> r.split(' ')
['court2', '13', '0', '2012', '9', '2']

Method 3

Change

r.split(' ')
a.split(' ')

to

r = r.split(' ')
a = a.split(' ')

Explanation: split doesn’t split the string in place, but rather returns a split version.

From documentaion:

split(...)

    S.split([sep [,maxsplit]]) -> list of strings

    Return a list of the words in the string S, using sep as the
    delimiter string.  If maxsplit is given, at most maxsplit
    splits are done. If sep is not specified or is None, any
    whitespace string is a separator and empty strings are removed
    from the result.


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x