2012-09-02 161 views
2

我有下面的python代碼。爲什麼python string split()沒有分裂

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) 

我得到以下日誌打印輸出。

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 

我得到了相同的日誌打印,如果不是的分裂(」「)我用split(),順便說一句。

爲什麼拆分不將結果拆分成6個條目的列表?我想問題在於涉及到http請求,因爲我在gae交互式控制檯中的測試獲得了預期的結果。

回答

7

split沒有修改字符串。它返回分割片段的列表。如果您想使用該列表,則需要將其分配給某些內容,例如r = r.split(' ')

4

split不分割原始字符串,而是返回一個列表

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

變化

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

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

說明:split不到位的字符串分割,而是返回一個分割版本。

從文件建立:

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. 
相關問題