r/PythonLearning • • 4d ago

Help Request where did the '\n' go?

using f.read().split() removes the \n escape sequence, why does that happen?

0 Upvotes

10 comments sorted by

12

u/Confident_Rod_9717 4d ago

From the built in docs, it seems unless you specify a separator, it splits on any whitespace character, not just space

>>> help(str.split)
Help on method descriptor split:

split(self, /, sep=None, maxsplit=-1) unbound builtins.str method
   Return a list of the substrings in the string, using sep as the separator string.

     sep
       The separator used to split the string.

       When set to None (the default value), will split on any
       whitespace character (including \n \r \t \f and spaces) and
       will discard empty strings from the result.
     maxsplit
       Maximum number of splits.
       -1 (the default value) means no limit.

   Splitting starts at the front of the string and works to the end.

   Note, str.split() is mainly useful for data that has been
   intentionally delimited.  With natural text that includes
   punctuation, consider using the regular expression module.

3

u/Waste-Moment1113 4d ago

Omg I didnt know that! Thank you

8

u/mc_pm 4d ago edited 4d ago

Read the docs. It's doing exactly what it is documented as doing.

1

u/Waste-Moment1113 4d ago

I am sorry but, I am new to python, what 'docs' are are you referring to here?

8

u/mc_pm 4d ago

The python docs, like this.

1

u/Waste-Moment1113 4d ago

Thank you.

3

u/Fun_Army2398 4d ago

Man people in r/PythonLearning are really down voting because a beginner hasn't seen the docs before? Y'all probably learned loops on friday and think you're a hacker now.

3

u/CptMisterNibbles 3d ago

Absolute loser behavior, but what do you expect from Reddit. Most posts here have more responses than upvotes, so any people are just auto downvoting what they think are easy/beginneer questions on a sub literally dedicated in part to doing exactly that.

Anyone downvoting this is just choosing to be a miserable NPC

2

u/Due-Mortgage-6854 4d ago

.split() treats \n as whitespace and removes it by default when splitting. If you want to keep it :

x = f.read().split(' ')

1

u/Careful_Exercise_956 3d ago

Looks like whe. Sorrow is read with a "." It is read as the end of a line in the python interpreter or compiler. And especially more specific when using the >>>help.