为什么python string split()不是split

2024-05-15 02:06:45 发布

您现在位置:Python中文网/ 问答频道 /正文

我有以下python代码。

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()而不是split(''),我会得到相同的日志打印输出,顺便说一句

为什么split不将结果分成一个包含6个条目的列表?我认为问题在于涉及到http请求,因为我在gae交互控制台中的测试得到了预期的结果。


Tags: 代码pyselfinfolenloggingviewsreservations
3条回答

split不拆分原始字符串,但返回一个列表

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

split不修改字符串。它返回一个分割块的列表。如果要使用该列表,则需要将其分配给具有的对象,例如r = r.split(' ')

改变

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.

相关问题 更多 >

    热门问题