String.strip() in Python

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

    strip does nothing but, removes the the whitespace in your string. If you want to remove the extra whitepace from front and back of your string, you can use strip.

    The example string which can illustrate that is this:

    In [2]: x = "something \t like     \t this"
    In [4]: x.split('\t')
    Out[4]: ['something ', ' like     ', ' this']
    

    See, even after splitting with \t there is extra whitespace in first and second items which can be removed using strip in your code.

    0 讨论(0)
  • 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)
    
    0 讨论(0)
  • 2021-01-30 03:53

    No, it is better practice to leave them out.

    Without strip(), you can have empty keys and values:

    apples<tab>round, fruity things
    oranges<tab>round, fruity things
    bananas<tab>
    

    Without strip(), bananas is present in the dictionary but with an empty string as value. With strip(), this code will throw an exception because it strips the tab of the banana line.

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2021-01-30 04:02

    strip removes the whitespace from the beginning and end of the string. If you want the whitespace, don't call strip.

    0 讨论(0)
提交回复
热议问题