Why does my code print twice the amount of spaces I expect? - python

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," ")

Related

Why is there no blank space printed when there is a print() after an end function?

print("where is", end = ' ')
print()
print("Blank line")
Why is there no blank space between these two lines of code? From what I have, heard, the print() prints a blank line, so why does having print() after the end function cause there to be no blank space?
I am aware that the end function means that the end character is defined by the last whitespace and not a new line.
print() works just the way you think it does.
However, the preceding line has a print statement that does not end with a newline character; instead it prints a space.
So this what is printed:
where is<space><newline>Blank line'
The <space> comes from the first print statement
The <newline> comes from the second print statement
You already know that Blank line comes from the third print statement
end = ' ' explicitly stops the first print from printing a newline. The output of the three statements is:
"where is " + "\n" + "Blank line\n"
i.e.
"where is \nBlank line\n"
Which results in:
where is
Blank line
In Python, print() function ends with a newline by default, however, the print() function has an option to modify that behavior. Using the end = ' ' replaces the \n with a blank space.
Python 3.9: Input and Output
Try using this
print("""where is
Blank line""")

I have issues of printing out the string correctly

I wanted the code to print out certain strings.
The issue was the the output was not what I expected, since it would print out something like this:
BruhBruh
BruhBruh
I was hoping for this:
Bruh
Bruh
How do I fix it?
def repeate(c,rep):
c=input("what str")
rep=int(input("how many times?"))
for i in range(rep):
print(c*rep)
return i
repeat=repeate(0,0)
print(repeat)
Add a space to the user input.
Change your line:
c=input("what str") + “ “
Now if the user enters “Dude”, c will be “Dude “.
by calling print(c*rep) you are printing out a catenation of rep instances of string c
and this gets repeated in cycle for i in range(rep): for additional rep times
to get string repeated certain amount of times you may use function join on the array of strings, e.g.
print(" ".join(['Bruh']*3))
alternately use print with default (crlf) terminator replaced with space char:
for i in range(3):
print("Bruh", end=" ")
also, both args of this function are useless -- you just set them in function body via input

difference between print(" str", a ) and print("str" + a )

I am a beginner with python3 and I use a lot print or the logging module to follow the code on the console. A simple example below: what's the difference between:
number = "seven"
print("I cooked " , number , " dishes")
and
number = "seven"
print("I cooked " + number + " dishes")
Internally the difference is that this example (no + sign):
number = "seven"
print("I cooked " , number , " dishes")
Is printing 3 separate string objects. "I cooked ", is object 1, number is object 2, and " dishes" is object 3. So this has 3 objects total.
In the second example (with the + sign):
number = "seven"
print("I cooked " + number + " dishes")
the 3 separate strings are first being concatted into 1 new string object before being printed to stdout. So this example has 4 objects total.
The print statement supports multiple ways of parsing values.
number = 'seven'
Examples: Different style of adding argument in print statement
print("I cooked " , number , " dishes")
C-Style formatting (old):
print("I cooked %s dishes" % number)
C-Style formatting (new) using fomat:
print("I cooked {} dishes ".format(number))
f-string style
print(f"I cooked {number} dishes")
String concatenating:
print("I cooked " + number + " dishes")
You don't necessary to stick with one style. You have various options of doing the same.
The operator + can be only used on strings.
The operator , can be used on any type, and adds a space before automatically.
In addition, + can be used not only in printing but to add one string to another while , cant.
(Note that in the two examples you have, by simply running them will show that the results are different, as the first one will have some words separated by double spaces.)
The print() function will take in strings, each string will be printed out with a ' ' between them:
print('hello', 'world')
Output:
hello world
That is because of the keyword argument, sep. By default, sep=' ', that is changeable by simply adding:
print('hello', 'world', sep='\n')
Output:
hello
world
The + operator will not add any separator, it will simply concatenate the strings:
print('hello' + 'world')
Output:
helloworld
As per PEP3105 print is considered as a function taking *args (several positional arguments).
To answer your question, the result is the same; however, your implementation is different. In the first case you give print multiple arguments to print, while in the second case you give print a concatenated string that you would like to print.
when using
number = "seven"
print("I cooked " , number , " dishes")
print gets 3 different objects (3 strings) as arguments, converts them to string and then prints.
However using
number = "seven"
print("I cooked " + number + " dishes")
means that first these three strings are concatenated and then passed as one object to print.
In reality, it means, that if you do for example
print('xxx' + 5 + 'yyy')
it will throw and error, as it is not possible to directly concatenate string and int types.
Also note following example:
#concatenating 3 strings and passing them as one argument to print
>>> print('xxx' + 'a' + 'yyy',sep=',')
xxxayyy
#passing 3 strings as 3 arguments to print
>>> print('xxx','a','yyy',sep=',')
xxx,a,yyy
You can notice, that in first example, although sep is used (thus it should separate 3 strigns with given separator) it does not work, because these strings are concatenated first and then passed as one argument to print. In the second example however, strings are passed as separated arguments, therefore sep=',' works, because print just knows that it should pass the separator between each given string.
Lets say a = "how are you" and b = "goodbye" which are 2 string variables.
If we do print(a, b):
The statement will print first a then b as separate strings outputted on one line:
Output:
> how are you goodbye
If we do print(a + b) the statement will concatenate these two variables a and b together:
Output:
> how are yougoodbye
(here there's no spacing due no white spacing in the print statement or the variables)

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 print spaces in 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.

Categories

Resources