Can someone tell me what split() does in python? I looked at the documentation and it confused me. | Sololearn: Learn to code for FREE!
Novo curso! Todo programador deveria aprender IA generativa!
Experimente uma aula grƔtis
+ 2

Can someone tell me what split() does in python? I looked at the documentation and it confused me.

9th Jun 2017, 2:39 PM
Shriram
Shriram - avatar
3 Respostas
+ 5
a="1:2:34:5" split_up = a.split(":") print(split_up ) Output: ['1', '2', '34', '5'] The variable 'a' is split (cut, tokenized, separated) into pieces, using ":" as the place to cut. The variable 'split_up' is a list of pieces that result from the splitting.
9th Jun 2017, 3:15 PM
Kirk Schafer
Kirk Schafer - avatar
+ 4
"Line separators" vary between Unix/Linux and Windows (important if you wish to split by lines): https://stackoverflow.com/a/454809 Escaping (with \) depends on whether the string actually contains backslashes. When processing (from the program's perspective, not the data's): \n : The backslash applies to "n" and has special meaning (end of line). \\ : The first backslash applies to the next character, which outputs a non-special \, and escape-processing ends (continuing with 'n'). \\n: The generated \ is NOT SPECIAL and is treated as output. The "n" is not interpreted and the string contains a literal backslash followed by 'n' ('\n'). a="\\n" --> creates a string "\n" (two characters long) a="\n" --> creates a string using the end of line sequence for the host operating system. (1 or 2 characters; see the link). You may want to split by the end-of-line sequence written by the OS that created the file (which may be different than where you are running Python)...just read the other comments about file reading at the link.
9th Jun 2017, 3:58 PM
Kirk Schafer
Kirk Schafer - avatar
+ 1
so suppose you have a variable with some very long string which is supposed to be in separate lines. do you use split ('\n) or split('\\n)?
9th Jun 2017, 3:23 PM
Shriram
Shriram - avatar