How to print spaces in Python? - python
In C++, \n is used, but what do I use in Python?
I don't want to have to use:
print (" ").
This doesn't seem very elegant.
Any help will be greatly appreciated!
Here's a short answer
x=' '
This will print one white space
print(x)
This will print 10 white spaces
print(10*x)
Print 10 whites spaces between Hello and World
print(f"Hello{x*10}World")
If you need to separate certain elements with spaces you could do something like
print "hello", "there"
Notice the comma between "hello" and "there".
If you want to print a new line (i.e. \n) you could just use print without any arguments.
A lone print will output a newline.
print
In 3.x print is a function, therefore:
print()
print("hello" + ' '*50 + "world")
Any of the following will work:
print 'Hello\nWorld'
print 'Hello'
print 'World'
Additionally, if you want to print a blank line (not make a new line), print or print() will work.
First and foremost, for newlines, the simplest thing to do is have separate print statements, like this:
print("Hello")
print("World.")
#the parentheses allow it to work in Python 2, or 3.
To have a line break, and still only one print statement, simply use the "\n" within, as follows:
print("Hello\nWorld.")
Below, I explain spaces, instead of line breaks...
I see allot of people here using the + notation, which personally, I find ugly.
Example of what I find ugly:
x=' ';
print("Hello"+10*x+"world");
The example above is currently, as I type this the top up-voted answer. The programmer is obviously coming into Python from PHP as the ";" syntax at the end of every line, well simple isn't needed. The only reason it doesn't through an error in Python is because semicolons CAN be used in Python, really should only be used when you are trying to place two lines on one, for aesthetic reasons. You shouldn't place these at the end of every line in Python, as it only increases file-size.
Personally, I prefer to use %s notation. In Python 2.7, which I prefer, you don't need the parentheses, "(" and ")". However, you should include them anyways, so your script won't through errors, in Python 3.x, and will run in either.
Let's say you wanted your space to be 8 spaces,
So what I would do would be the following in Python > 3.x
print("Hello", "World.", sep=' '*8, end="\n")
# you don't need to specify end, if you don't want to, but I wanted you to know it was also an option
#if you wanted to have an 8 space prefix, and did not wish to use tabs for some reason, you could do the following.
print("%sHello World." % (' '*8))
The above method will work in Python 2.x as well, but you cannot add the "sep" and "end" arguments, those have to be done manually in Python < 3.
Therefore, to have an 8 space prefix, with a 4 space separator, the syntax which would work in Python 2, or 3 would be:
print("%sHello%sWorld." % (' '*8, ' '*4))
I hope this helps.
P.S. You also could do the following.
>>> prefix=' '*8
>>> sep=' '*2
>>> print("%sHello%sWorld." % (prefix, sep))
Hello World.
rjust() and ljust()
test_string = "HelloWorld"
test_string.rjust(20)
' HelloWorld'
test_string.ljust(20)
'HelloWorld '
Space char is hexadecimal 0x20, decimal 32 and octal \040.
>>> SPACE = 0x20
>>> a = chr(SPACE)
>>> type(a)
<class 'str'>
>>> print(f"'{a}'")
' '
Tryprint
Example:
print "Hello World!"
print
print "Hi!"
Hope this works!:)
this is how to print whitespaces in python.
import string
string.whitespace
'\t\n\x0b\x0c\r '
i.e .
print "hello world"
print "Hello%sworld"%' '
print "hello", "world"
print "Hello "+"world
Sometimes, pprint() in pprint module works wonder, especially for dict variables.
simply assign a variable to () or " ", then when needed type
print(x, x, x, Hello World, x)
or something like that.
Hope this is a little less complicated:)
To print any amount of lines between printed text use:
print("Hello" + '\n' *insert number of whitespace lines+ "World!")
'\n' can be used to make whitespace, multiplied, it will make multiple whitespace lines.
In Python2 there's this.
def Space(j):
i = 0
while i<=j:
print " ",
i+=1
And to use it, the syntax would be:
Space(4);print("Hello world")
I haven't converted it to Python3 yet.
A lot of users gave you answers, but you haven't marked any as an answer.
You add an empty line with print().
You can force a new line inside your string with '\n' like in print('This is one line\nAnd this is another'), therefore you can print 10 empty lines with print('\n'*10)
You can add 50 spaces inside a sting by replicating a one-space string 50 times, you can do that with multiplication 'Before' + ' '*50 + 'after 50 spaces!'
You can pad strings to the left or right, with spaces or a specific character, for that you can use .ljust() or .rjust() for example, you can have 'Hi' and 'Carmen' on new lines, padded with spaces to the left and justified to the right with 'Hi'.rjust(10) + '\n' + 'Carmen'.rjust(10)
I believe these should answer your question.
Related
Formatting a line with spaces at the beginning
Consider below piece of code line = "I am writing a question" print('{0: >10}'.format(line)) This does not work as expected. I expected output to be ' I am writing a question' I know I can achieve this by other means like printing the spaces first using one print statement and then print the sentence. But curious to know what I might be doing wrong.
Your line is longer than 10 characters; the width is a minimal value and applies to the whole column. If you wanted to add 10 spaces, always, prefix these before the format: print(' {0}'.format(line)) If you always wanted to right-align the string in a column of 33 characters (10 spaces and 23 characters for your current line), then set the column width to that instead: print('{0:>33}'.format(line)) Now, when your line value is longer or shorter, the amount of whitespace will be adjusted to make the output 33 characters wide again. Demo: >>> line = "I am writing a question" >>> print(' {0}'.format(line)) I am writing a question >>> print('{0:>33}'.format(line)) I am writing a question >>> line = "question" >>> print('{0:>33}'.format(line)) question
There is a built in method : https://docs.python.org/2/library/stdtypes.html#str.rjust v = 'hi' print v.rjust(4, ' '); prints ' hi'
Why does my code print twice the amount of spaces I expect?
Python provides a built-in function called len that returns the length of a string, so the value of len('allen') is 5. Write a function named right_justify that takes a string named s as a parameter and prints the string with enough leading spaces so that the last letter of the string is in column 70 of the display. Author's solution: def right_justify(s): print (' '*(70-len(s))+s) >>> right_justify('allen') My solution: def right_justify(s): space_count=70-len(s) for i in range(0,space_count,1): print " ", print s strng=raw_input("Enter your desired string:") print len(strng) right_justify(strng) The output of my code is different than the output of author's code: I am getting twice as many spaces, e.g. 130 instead of 65. But it seems to me that the two pieces of code are logically equivalent. What am I overlooking?
The problem is with your print statement print " ", will print two spaces for each iteration of the loop. When terminating the print statement with a comma, subsequent calls will be delimited by a space. On a side note, another way to define your right_justify function would be def right_justify(s): print '%70s' % s
The print " ", line actually prints two spaces (one from the " ", one from the ,). You could replace it with print "", to have your function work identically to the original.
Your code has 130 spaces, the author's code has 65 spaces. This is because print " ", ...adds a space. What you want is: print "",
I would prefer the function str.rjust(70," ") which does the trick, I think, like so: strng.rjust(70," ")
Python print statement on new line
I have a program that prints out strings from an array like this: for x in strings print x, Which works fine, the strings all print on the same line which is what I want, but then I also have to print out a string that isn't part of the array on a new line. Like this: for x in strings: print x, print second_name Which ends up all printing on the same line. I want second_name to print on a newline though, how do I do this?
Use the newline character \n: print '\n' + second_name
I personally think it would be best to use str.join here: print " ".join(strings) print second_name The for-loop just seems like overkill.
The most direct solution is that if you used "print" without final newline in a cycle, add it after this cycle; so the code will look like for x in strings: print x, print ## this terminates the first output line print second_name This is kind of the most proper usage of print "API" according to its concepts. OTOH the answer by K DawG does essentialy the same in other way, putting the default ending '\n' at beginning of the next "print", and, stream nature of stdout makes results of these two variants identical. NB your construct isn't portable directly to Python3. Python2's print adds a space before each argument unless output isn't at beginning of line. Python3's separator is applied between arguments, but not before the first one in a line. So this manner (cloned from BASIC) isn't perspective and should be replaced with an own manner, like: out = '' for x in strings: out += ' ' + x print(out[1:]) print(second_name) but, " ".join(strings) is generally faster and more clear to read.
How to make a sentence in Python?
Im using Python 3.2 on Win7. I wrote this using ASCII code: print (''.join((chr(i+22) for i in (50,75,90,90,99)))) print (''.join((chr(j+22) for j in (44,83,92,94,82,78,75,99,11)))) which as a result writes: Happy Birthday! Now, I'd like to join these two words in one sentence, so it writes: Happy Birthday! It seems like a simple thing to do, but I'm new at Python, so could someone help me? Thanks :)
Do you mean like this? print (''.join((chr(i+22) for i in (50,75,90,90,99,10,44,83,92,94,82,78,75,99,11))))
To have them on the same line, and the end of the first print statement, type in the parameter end=" ", so the next print statement will print on the same line.
its simple.. just use + operator. print (''.join((chr(i+22) for i in (50,75,90,90,99))))+" "+ (''.join((chr(j+22) for j in (44,83,92,94,82,78,75,99,11))))
You can ask print() not to add a newline: print(..., end='') end, by default, is set to \n. For your sample, that'd be: print(''.join((chr(i+22) for i in (50,75,90,90,99))), end=' ') print(''.join((chr(j+22) for j in (44,83,92,94,82,78,75,99,11)))) printing a space instead of a newline after Happy. You could also include the space in your list of ASCII codepoints; ASCII space is 32, but you add 22 to your values, so including 10 should do it: print(''.join((chr(i+22) for i in (50,75,90,90,99,10,44,83,92,94,82,78,75,99,11))))
Print your output using string formatting: s1 = ''.join((chr(i+22) for i in (50,75,90,90,99))) s2 = ''.join((chr(j+22) for j in (44,83,92,94,82,78,75,99,11)))) print("%s %s" % (s1, s2))
print a string in python left justified with an offset
I am using Python 2.4. I would like to print a string left justified but with an "offset". By that I mean, print a string with a set number of spaces before it. Example: Print string "Hello" in a space of width 20, left justified, but five spaces inserted before the string. " Hello " #(The string has 5 spaces prior, and 10 space after) print "Hello".ljust(20) #does not cut it. I could use the following as a workaround: print " ", "Hello".ljust(15) Is there a better approach than printing a string of 5 spaces. Thank you, Ahmed.
Not really. >>> ' %-15s' % ('Hello',) ' Hello '