print statement returning without space in python - 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())

Related

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

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

multiple whitespaces inside print

how can get a desired amount of whitespaces in a print
print("a",'','','','','','',"a")
can not be written as
print("a",''*6,"a")
does not work. Please help
'' is a null string, not a space. In the first example, print itself is inserting a space between each of the 8 arguments; in the second, it's inserting a space between each of the 3 arguments.
If you want
a a
you can use
print('a', ' '*4, 'a') # a, space, 4-spacces, space, a
or
print('a', 'a', sep=' '*6) # a separator of 6 spaces
or simply
print('a a')
You can use the sep keyword
print("a", "a", sep=" "*6)
prints
a a
I think you can do it likethis :
print("a"," "*6,"a")

Two if statements on same line

Very new to this, and cant seem to get these two to print on the same line. Python 3
isCold= sys.argv[1] == 'True'
isRainy= sys.argv[2] == 'True'
if isCold:
print "cold and",
else:
print "warm and ",
if isRainy:
print('rainy')
else:
print('dry')
Keep getting:
cold and
rainy
I need:
cold and rainy
print has an end parameter whose default value is \n, a newline. Call the first prints with print("cold and", end="") and they won't skip to the next line.
on the end of each print statement there is a \n which means "enter" or "new line"
build your str with + signs and print the build-up string at the end.
Each call to print will result in the text being printed on its own line because a new line character is appended. This is mentioned in the documentation -
print(*objects, sep=' ', end='\n', file=sys.stdout, flush=False)
The default value for end is why you are seeing a new line after each call to print.
What you could do is build a string variable in your conditional statements and then only print once at the end -
output = ''
if isCold:
output += "cold and"
else:
output += "warm and "
if isRainy:
output += 'rainy'
else:
output += 'dry'
print output
In addition, I see you are assigning string values instead of boolean values. In python "True" is not the same as True. You should assign proper boolean values. Take the following example -
myBool = 'True'
if myBool:
print('Bool is truthy')
myBool = 'False'
if myBool:
print('Bool is STILL truthy')
myBool = False
if myBool:
print('This should not be printed')
The print() function in Python takes more than one argument. One of the arguments is the end.
Now usually, the print function has a default argument of end="\n", where \n is newline. This is the reason why your output comes as:
cold and
rainy - instead of:
cold and rainy
One solution to the many is to specify end. The end determines what the printed string will end with. For example:
>>> print("It is raining", end="!")
It is raining!
>>> print("What", end=",")
What,
So to get your output on the same line, you can try the following:
print("cold and", end="")
This will override the default argument of '\n' and you will get the desired output.
Rather than two print calls, you can create a single string and print once.
Consider:
print("{} and {}".format(("warm", "cold")[isCold], ("dry", "rainy")[isRainy]))
In this case you are using the boolean value of each iCold and isRainy to index a tuple of strings to create a single string with all combinations.
You can also use the Python ternary to accomplish the same:
print("{} and {}".format("cold" if isCold else "warm", "rainy" if isRainy else "dry"))
You can also try this:
if isCold:
a = "cold and "
else:
b = "warm and "
if isRainy:
print(a+'rainy')
else:
print(b+'dry')
Use a logical and:
if sys.argv[1] == 'True' and sys.argv[2] == 'True':
print("cold and rainy)

Python: Remove words from a given string

I'm quite new to programming (and this is my first post to stackoverflow) however am finding this problem quite difficult. I am supposed to remove a given string in this case (WUB) and replace it with a space. For example: song_decoder(WUBWUBAWUBWUBWUBBWUBC) would give the output: A B C. From other questions on this forums I was able to establish that I need to replace "WUB" and to remove whitespace use a split/join. Here is my code:
def song_decoder(song):
song.replace("WUB", " ")
return " ".join(song.split())
I am not sure where I am going wrong with this as I the error of WUB should be replaced by 1 space: 'AWUBBWUBC' should equal 'A B C' after running the code. Any help or pointing me in the right direction would be appreciated.
You're close! str.replace() does not work "in-place"; it returns a new string that has had the requested replacement performed on it.
Return a copy of the string with all occurrences of substring old replaced by new. If the optional argument count is given, only the first count occurrences are replaced.
Do this instead:
def song_decoder(song):
song = song.replace("WUB", " ")
return " ".join(song.split())
For example:
In [14]: song_decoder("BWUBWUBFF")
Out[14]: 'B FF'
Strings are immutable in Python. So changing a string (like you try to do with the "replace" function) does not change your variable "song". It rather creates a new string which you immediately throw away by not assigning it to something. You could do
def song_decoder(song):
result = song.replace("WUB", " ") # replace "WUB" with " "
result = result.split() # split string at whitespaces producing a list
result = " ".join(result) # create string by concatenating list elements around " "s
return result
or, to make it shorter (one could also call it less readable) you can
def song_decoder(song):
return " ".join(song.replace("WUB", " ").split())
Do the both steps in a single line.
def song_decoder(song):
return ' '.join(song.replace('WUB',' ').split())
Result
In [95]: song_decoder("WUBWUBAWUBWUBWUBBWUBC")
Out[95]: 'A B C'

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

Categories

Resources