The reason why this happens is because you are using commas in your print statements. In python there are a few ways to give the print statement multiple variables, you seem to be mixing two of them together. The ways are as follows.
- Concatenate the string.
print('The ratio of ' + str(number1) + ' + ' + str(number2) + ' is ' + str(ration12) + '.')This way is probably the most basic way. It will join the strings without adding any characters in between them (e.g. no spaces in between unless you add them explicitly.) Also note, that string concatenation won't automatically cast the integers to a string for you. - Pass print multiple arguments.
print('The ratio of', number1, '+', number2, 'is', ration12, '.')This will automatically add spaces between each argument and is what is happening in your case. The separator (which defaults to a space) can be changed by passing a keyword argument to the print function. For example,print('i = ', i, sep='') - Use string formatting.
print('The ratio of {} + {} is {}.'.format(number1, number2, ratio12))This way is the most readable and often the best way. It will replace the '{}' sections in you 'template' string with the arguments based into the format function. It does this in order, however you can add an index like this '{0}' to explicitly use an argument by index.
The reason why this happens is because you are using commas in your print statements. In python there are a few ways to give the print statement multiple variables, you seem to be mixing two of them together. The ways are as follows.
- Concatenate the string.
print('The ratio of ' + str(number1) + ' + ' + str(number2) + ' is ' + str(ration12) + '.')This way is probably the most basic way. It will join the strings without adding any characters in between them (e.g. no spaces in between unless you add them explicitly.) Also note, that string concatenation won't automatically cast the integers to a string for you. - Pass print multiple arguments.
print('The ratio of', number1, '+', number2, 'is', ration12, '.')This will automatically add spaces between each argument and is what is happening in your case. The separator (which defaults to a space) can be changed by passing a keyword argument to the print function. For example,print('i = ', i, sep='') - Use string formatting.
print('The ratio of {} + {} is {}.'.format(number1, number2, ratio12))This way is the most readable and often the best way. It will replace the '{}' sections in you 'template' string with the arguments based into the format function. It does this in order, however you can add an index like this '{0}' to explicitly use an argument by index.
Some string formating makes your live easier:
number1 = 1
number2 = 2
ratio12 = number1 / number2
print('The ratio of {} + {} is {}.'.format(number1, number2, ratio12))
Output:
The ratio of 1 + 2 is 0.5.
This is what I have written so far:
length = len(input("What is your name?\n"))
print("The length of your name is ",length,".")
Now, this is my output:
What is your name?
Shary
The length of your name is 5 .I would like my output to be like the following: "The length of your name is 5."
As you can imagine, by placing a comma next to the Integer length, I have an extra space I would like to take care of. I am new to Python so I do not really know how to solve this.
Any help would be greatly appreciated.
You need to concatenate it:
print first_name, "was born on", month, day+',', year, "."
UPDATE: as @sr2222 points out, this will print an extra space before the period. If you want to avoid it (and assuming that year is a string):
print first_name, "was born on", month, day+',', year + "."
Put quotation marks around it.
print first_name, "was born on", month, day+',', year +'.'
Though really, you should clean this up, as combining a bunch of different string concatenation mechanisms in a single line gets hard to read.
print first_name + " was born on " + month + ", " + day + ", " + year + "."
There is also the big wide world of string formatting, of course.
Use string formatting:
print "i is equal to %d." % i
As of Python 2.6, strings have a .format() function that can alternatively be used:
>>> print "i is equal to {}".format(i)
i is equal to 5
It's useful if you have a placeholder that's used multiple times in the format string:
>>> print "i={0}, a.k.a. 'i is equal to {0}.'".format(i)
i=5, a.k.a. 'i is equal to 5.'
You can also concatenate like this,
print "i is equal to " + str(i) + "."
When you separate values with comma in print() it will add spaces. Since you are using Python 3 you could instead use f-strings like this
print(f"{name}, you were born in {year}.")
There's great documentation on it here: https://docs.python.org/3/tutorial/inputoutput.html#
You should indeed use f strings as @Sandsten has said above, but just for your info there is the old way as below...
print('{0}, you were born in {1}.').format(name, year)
Use an f string, just like this!
import datetime
from datetime import date
today = date.today()
user_name = input('What is your name? ')
user_age = int(input('How old are you? '))
print(f"Hello {user_name}! You were born in {today.year - user_age}.")
You can convert the year into a string by wrapping it in the str() function and then use + to concatenate.
Just define a function to fix one sentence, then use list comprehension to construct a new list from the old:
def fix_sentence(str):
if str == "": # Don't change empty strings.
return str
if str[-1] in ["?", ".", "!"]: # Don't change if already okay.
return str
if str[-1] == ",": # Change trailing ',' to '.'.
return str[:-1] + "."
return str + "." # Otherwise, add '.'.
orig_sentences = ['Hi how are you?', 'I am good', 'Great!', 'I am doing good,', 'Good.']
fixed_sentences = [fix_sentence(item) for item in orig_sentences]
print(fixed_sentences)
This outputs, as requested:
['Hi how are you?', 'I am good.', 'Great!', 'I am doing good.', 'Good.']
With a separate function, you can just improve fix_sentence() if/when new rules need to be added.
For example, being able to handle empty strings so that you don't get an exception when trying to extract the last character from them, as per the first two lines of the function.
According to De Morgan's laws, you should change to:
b = b + '.' if (not b.endswith('.')) and (not b.endswith('!')) and (not b.endswith('?')) else b
You can simplify to:
b = b + '.' if b and b[-1] not in ('.', '!', '?') else b
Try this:
print ("{} + {} is equal to {}.".format(num1, num2, add(num1, num2)))
This makes use of the format() method documented here.
There are a couple of things you can do:
print (str(num1) + "+" + str(num2) + " is equal to " + str(add(num1, num2)) +".")
What this does is to convert the numbers to strings and append them into one big string which is then printe.
Much better is to use use a formatter:
print ("{0} + {1} is equal to {2}.".format(num1, num2, add(num1, num2))
In this example you define a "format" where {n} are replaced by the values passed in the format function. This produces a string that is then printed.
The second way is more elegant and easy to follow in my opinion, so I suggest using that.
You can create a class. For this example, .myfunc() will return 1 if the number is greater than 0, otherwise, it will return 0:
class s:
def __init__(self, value):
self.value = value
def myfunc(self):
if self.value > 0:
return 1
else:
return 0
num = s(20)
print(num.myfunc())
Output:
1
The .func() is specially used for objects belonging to a particular class.
For example, .split() is specially built for strings.
You can also create them by creating a class and then defining a function in that class.