What is the difference between "+" and "," when printing? [duplicate] - python

This question already has answers here:
Difference between using commas, concatenation, and string formatters in Python
(2 answers)
Closed 2 months ago.
What is the difference between these two pieces of code?
name = input("What is your name?")
print("Hello " + name)
name = input("What is your name?")
print("Hello ", name)
I'm sorry if this question seems stupid; I've tried looking on Google but couldn't find an answer that quite answered my question.

In this example, you have to add an extra whitespace after Hello.
name = input("What is your name?")
print("Hello " + name)
In this example, you don't have to add an extra whitespace (remove it). Python automatically adds a whitespace when you use comma here.
name = input("What is your name?")
print("Hello ", name)

print('a'+'b')
Result: ab
The above code performs string concatenation. No space!
print('a','b')
Result: a b
The above code combines strings for output. By separating strings by comma, print() will output each string separated by a space by default.

According to the print documentation:
print(*objects, sep=' ', end='\n', file=None, flush=False)
Print objects to the text stream file, separated by sep and followed by end.
The default separator between *objects (the arguments) is a space.
For string concatenation, strings act like a list of characters. Adding two lists together just puts the second list after the first list.

print() function definiton is here: docs
print(*objects, sep=' ', end='\n', file=None, flush=False)
Better to explain everything via code
name = "json singh"
# All non-keyword arguments are converted to strings like str() does
# and written to the stream, separated by sep (which is ' ' by default)
# These are separated as two separated inputs joined by `sep`
print("Hello", name)
# Output: Hello json singh
# When `sep` is specified like below
print("Hello", name , sep=',')
# Output: Hello,json singh
# However the function below evaluates the output before printing it
print("Hello" + name)
# Output: Hellojson singh
# Which is similar to:
output = "Hello" + name
print(output)
# Output: Hellojson singh
# Bonus: it'll evaluate the input so the result will be 5
print(2 + 3)
# Output: 5

Related

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)

I cannot get rid of this space

I have the simple code:
answer= input("Have you started your first homework? ")
print("Your answer was:", answer,"!")
However every time I run this it prints the answer there is a space before the "!".
I cannot find a way to make the exclamation follow the answer directly. Why and how can I do that?
If you want to print the answer, you have a few options:
# Multiple args
print("Your answer was: ", answer, "!", sep="")
# String formatting
print("Your answer was: {}!".format(answer))
# String concatenation
print("Your answer was: " + answer + "!")
Python 3.6+:
# f-strings
print(f"Your answer was: {answer}!")
print has an argument called sep which, by default, is set to ' ' (a space). It will add that separator between every argument.
print function automatically adds a space between comma separated arguments.
So if you don't want that comma, don't pass them as separate arguments and use string formatting instead e.g.:
print("Your answer was:", "{}!".format(answer))
Here i've concatenated the strings using str.format:
"{}!".format(answer)
If you're in Python 3.6 or later, you can use f-strings:
f"{answer}!"
You can even use the printf style formatting:
"%s!" % answer
Try this:
print("Your answer was: "+answer"+"!")

print statement returning without space in python

This is my code:
class Student(Person):
def __init__(self, firstName, lastName, idNumber,scores):
self.firstName = firstName
self.lastName = lastName
self.idNumber = idNumber
self.testscores = scores
def calculate(self):
average = sum(self.testscores) / len(self.testscores)
if average>=90 and average<=100 :
return'O'
elif average>=80 and average<90 :
return'E'
elif average>=70 and average<80 :
return'A'
elif average>=55 and average<70 :
return'P'
elif average>=40 and average<55 :
return'D'
else:
return'T'
The statement : print("Grade: ", s.calculate()) returns Grade: O (two spaces) instead of Grade: O (single space).
Since the above print statement is in locked stub code I can't modify it.
Is there anyway I can remove the extra space while returning from calculate function?
Edit: For better understanding of the problem consider this
image
in which the only difference is in my output's and expected output's third statement because of additional space.
The print function prints each of its arguments with a space as a delimiter already, so by adding a space in "Grade: ", you're making it print another space between the colon and the grade. Simply replace "Grade: " with "Grade:" and it will output without the extra space.
You can specify sep='', i.e. an empty string:
print('Grade: ', s.calculate(), sep='')
Or you can remove the space from your first argument:
print('Grade:', s.calculate())
Alternatively, you can use string formatting:
print(f'Grade: {s.calculate()}') # 3.6+
print('Grade: {}'.format(s.calculate())) # pre-3.6
To troubleshoot such problems, you can use the built-in help, which tells you the default argument for sep is a single space:
help(print)
print(...)
print(value, ..., sep=' ', end='\n', file=sys.stdout, flush=False)
...
sep: string inserted between values, default a space.
...
Interestingly, the official docs have got it wrong:
print(*objects, sep=' ', end='\n', file=sys.stdout, flush=False)
Print objects to the text stream file, separated by sep and followed
by end. sep, end, file and flush, if present, must be given as keyword
arguments.
Since the above print statement is in locked stub code I can't modify it.
Is there anyway I can remove the extra space while returning from calculate function?
If I not misunderstand, you can change caculate function, but not print, and you want just see one space in output, and you are in python3.
Then you can use backspace \b, change E.g. return 'O' to return '\bO', and other return need to be changed also.
A simple code for your quick test:
def fun():
return 'O'
def fun2():
return '\bO'
print("Grade: ", fun())
print("Grade: ", fun2())

Removing Space between variable and string in Python

My code looks like this:
name = Joe
print "Hello", name, "!"
My output looks like:
Hello Joe !
How do I remove the space between Joe and !?
There are several ways of constructing strings in python. My favorite used to be the format function:
print "Hello {}!".format(name)
You can also concatenate strings using the + operator.
print "Hello " + name + "!"
More information about the format function (and strings in general) can be found here:
https://docs.python.org/2/library/string.html#string.Formatter.format
6 Years Later...
You can now use something called f-Strings if you're using python 3.6 or newer. Just prefix the string with the letter f then insert variable names inside some brackets.
print(f"Hello {name}")
a comma after print will add a blank space.
What you need to do is concatenate the string you want to print; this can be done like this:
name = 'Joe'
print 'Hello ' + name + '!'
Joe must be put between quotes to define it as a string.
>>> print (name)
Joe
>>> print('Hello ', name, '!')
Hello Joe !
>>> print('Hello ', name, '!', sep='')
Hello Joe!
You can also use printf style formatting:
>>> name = 'Joe'
>>> print 'Hello %s !' % name
Hello Joe !
One other solution would be to use the following:
Print 'Hello {} !'.format(name.trim())
This removes all the leading and trailing spaces and special character.

Concatenating strings in python without spaces [duplicate]

This question already has answers here:
How to print without a newline or space
(26 answers)
Closed 6 years ago.
How can I print my strings so that there are no spaces between each output.
name_input = str(input("Please enter your name"))
name_input = name_input.strip()
name_input = name_input.lower()
first_letter = name_input[0]
first_space = name_input.find(" ")
last_name = name_input[first_space:]
last_name_3 = last_name[0:4]
random_number = random.randrange(0,999)
print("*********************************************")
print("Username Generator")
print("*********************************************")
print(first_letter + last_name_3, random_number)`
Incorrect output: b fir 723
what I require: bfir723
use the separator parameter to the print function, to remove the space by passing in an argument with no space.
Like this:
print(first_letter, last_name_3, random_number, sep='')
The default separator is a space. Specification is here:
https://docs.python.org/3/library/functions.html#print
You need to use strip() function for this:
print(first_letter.strip() + last_name_3.strip() + str(random_number).strip())
You don't need strip() and sep=''
You only need one or the other, but sep='' is cleaner and more beautiful
You could also just do
print(first_letter + last_name + str(random_number))
It turns out a combination of .strip() and ,sep='' was required to print correctly:
print(first_letter.strip() + last_name_3.strip(), random_number, sep="")

Categories

Resources