Reputation:
name="D. Perkins "
age="69"
ethnicity="black"
print(name,"\n",age,ethnicity)
Im new and experimenting with functions in python, this one in particular results in:
D. Perkins
69 black
^
this gap here is what I'm trying to solve, how would I do this ? Particularly in one string. Is there a better way to start a new line?
Upvotes: 0
Views: 50
Reputation: 5951
The reason you are getting an extra space there, is because the print() function inserts a separator between each argument. Because you did not specify a separator, a space is used.
print(name,"\n",age,ethnicity)
results as:
name + " " + "\n" + " " + age + " " + ethnicity
That space after the newline is your problem.
For you to get a new line without a leading space on the next line, concatenate your string outside of the print function like so:
lines = name + "\n" + age + " " + ethnicity
print(lines)
Python takes a little getting used to. Once you learn the basics, it is a very powerful language.
Upvotes: 0
Reputation: 300
You can use sep="\n"
in print function,
print(name, age+ethnicity, sep="\n")
Upvotes: 2
Reputation: 1988
You could use string interpolation here in numerous ways, e.g. if you are using Python 3.6 or newer
name="D. Perkins "
age="69"
ethnicity="black"
print(f"{name}\n{age} {ethnicity}")
or using string formatting
print("{n}\n{a} {e}".format(n=name, a=age, e=ethnicity))
Upvotes: 2