String.strip() in Python

后端 未结 5 1940
感情败类
感情败类 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:58

    If you can comment out code and your program still works, then yes, that code was optional.

    .strip() with no arguments (or None as the first argument) removes all whitespace at the start and end, including spaces, tabs, newlines and carriage returns. Leaving it in doesn't do any harm, and allows your program to deal with unexpected extra whitespace inserted into the file.

    For example, by using .strip(), the following two lines in a file would lead to the same end result:

     foo\tbar \n
    foo\tbar\n
    

    I'd say leave it in.

提交回复
热议问题