r/CodingHelp • u/happyfuckincakeday • Jul 13 '20
[Python] TIL about the "sep" parameter of print() in Python3 and you should know it too!
Say you have an array of items.
array = ["Joe", "2", "Ted", "4.98", "14", "Sam", "void *", "42", "float", "smurfs", "5006"]
Say you want to return/print the items in the array each on their own individual line simply write
print(*array, sep=\n)
and you'll get a list of items that looks like this:
Joe
2
Ted
4.98
14
Sam
void *
42
float
smurfs
5006
The 'sep' parameter allows you to modify space that separates each item in the array. By default that separator is a space called "softspace". In the above example you're modifying the space to be \n or a new line.
Another example:
print('W', 'E', 'S', 'T', sep='') Output = WEST The space has been removed from between the letters.
print('07', '13', '2020', sep='/') Output = 07/13/2020 The space has been replaced with a slash to format the date.
1
Jul 14 '20
Hwy! I'm new to Python 3 (and programming in general). Does \n mean separating into individual lines or is it something else? Can you elaborate?
2
2
u/randomtempaccount123 Beginner Coder Jul 15 '20
Yeah, basically, the forward slash means it is a special character, and the \n is a newline character. There are also other special characters, but idk them all
1
u/Renavin Jul 14 '20
There are other ones too! Python's print function is one of the reasons I love the language.
1
1
u/Python4fun Professional Coder Jul 14 '20
It also makes it easy to create comma or pipe delimited data files.
6
u/jonassjoh Jul 13 '20
You can also write
print('\n'.join(arr)). This will also allow you to store the resulting string in a variable, I'm not sure if that is possible with the other method.Edit: Or why not use:
which is very nice for almost any data type.