Print multiple lines in one expression without spaces
So for my first project, this is a simple program that prints your class name, which one you are in, and which school you attended. The only thing that bothers me is one of them, I have to use one operator print()
for all of this, and I need to format it so that each piece of information is on a different line.
What I want for the format:
first_name, last_name course_id, course_name, email school
But i get
first_name, last_name course_id, course_name, email school
How do I remove a space?
My code looks like this:
first_name = 'Daniel'
last_name = 'Rust'
course_id = 'Csci 160'
course_name = 'Computer Science 160'
email = 'blah@gmail.com'
school= 'Red River Highschool'
#variables printed for B
print(first_name, last_name, '\n', course_id, course_name, email, '\n', school, '\n')
source to share
print
inserts a space between each argument. You can disable this by adding , sep=''
after the last '\n'
, but then between first_name
and last_name
there should be no gaps or between course_id
and course_name
etc. You can then proceed to insert , ' '
manually where needed in the statement print
, but at this point it would be easier to just give print
one argument, formed by concatenating strings together with explicit spaces:
print(first_name + ' ' + last_name + '\n' + course_id + ' ' + course_name
+ ' ' email + '\n' + school + '\n')
source to share
As mentioned here , you can use an argument sep=''
for a function print()
. This will allow you to set the separator between the printed values (which is the default space) to whatever you want, including a blank line. Remember to add spaces between the values you want to separate. For example.
print(first_name, ' ', last_name, '\n', course_id, [...], sep='')
There's a better way to do this using the format()
string method , but your professor will probably save the one in the next lesson, so I won't go into detail on this for now. Follow the link to the Python docs and read the "String Format Syntax" section if you want more details. I'll just show you an example of what your code looks like with format()
:
print("{} {}\n{} {} {}\n{}".format(first_name, last_name, course_id, course_name, email, school))
Note at \n
the end, as it print()
automatically adds a new line unless you tell it otherwise.
source to share
I recommend reading str.format () to print your information.
The spaces in your view come from the fact that you called the print function passing in a list of strings, instead of passing a single string to the print function.
print(first_name + ' ' + last_name + '\n' + course_id + ' ' + course_name + ' ' + email + '\n' + school)
gives
Daniel Rust
Csci 160 Computer Science 160 blah@gmail.com
Red River Highschool
source to share