String.strip() in Python

后端 未结 5 1873
感情败类
感情败类 2021-01-30 03:07

While learning about python, I came upon this code, which takes a text file, splits each line into an array, and inserts it into a custom dictionary, where the array[0] is the k

5条回答
  •  没有蜡笔的小新
    2021-01-30 03:53

    In this case, you might get some differences. Consider a line like:

    "foo\tbar "
    

    In this case, if you strip, then you'll get {"foo":"bar"} as the dictionary entry. If you don't strip, you'll get {"foo":"bar "} (note the extra space at the end)

    Note that if you use line.split() instead of line.split('\t'), you'll split on every whitespace character and the "striping" will be done during splitting automatically. In other words:

    line.strip().split()
    

    is always identical to:

    line.split()
    

    but:

    line.strip().split(delimiter)
    

    Is not necessarily equivalent to:

    line.split(delimiter)
    

提交回复
热议问题