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"+"!")
Related
n=str(input("Enter your name"))
a=str(input("Where do you live?"))
print("Hello",n,"How is the weather at",a,"?")
How to Remove space between {a & ?} in the print statement?
An f-string will give you better control over the exact formatting:
print(f"Hello {n}. How is the weather at {a}?")
Commas in python add a space in the output.
No need to use str as inputs in python are already treated as strings.
You can use this:
n = input("Enter your name")
a = input("Where do you live?")
print("Hello",n,"How is the weather at",a+"?")
This concatenates the two strings.
OR
n = input("Enter your name")
a = input("Where do you live?")
print(f"Hello {n}! How is the weather at {a}?")
This is called f-strings. It formats the string so you can put the value of a variable in the output.
You can simply do it by using end inside the print
by default its value is \n and if you set it an empty string ''
it won't add anything(or any space).
after printing a and the ? will print exactly after that.
so you can write the code below:
print("Hello",n,"How is the weather at",a, end='')
print("?")
So basically, i am trying to get the user to input something like "123" and recieve the output "3 2 1"
but i cant figure out how to add the spaces
# current code
number = str(input("Type out a number with more then 1 charachter: "))
print("Original number:", number)
print("Number in reverse:", number[::-1])
I apologize in advance, im really new to programming.
Use str.join:
print("Number in reverse:", ' '.join(number[::-1]))
Or use an iterator reversed:
print("Number in reverse:", ' '.join(reversed(number)))
Use str.join:
print("Number in reverse:", " ".join(number[::-1]))
You can use str.join:
print("Number in reverse:", ' '.join(number[::-1]))
Here a space or ' ' is added between the characters.
The join() method returns a string created by joining the elements of
an iterable by string separator. exmaples for iterable objects are
strings and lists.
I am trying to position an input within a string in python.
For example, the console will read "I am ___ years old", and the input value completes the sentence. Is there a way to do this?
Not entirely sure what you want. If you just want the input to be placed into that string, you can, among others, use the new format strings (or just str.format, or the % operator):
age = input("What is your age? ")
print(f"I am {age} years old")
If your string actually has that ___ section and you want to insert the age there, you can first replace that with a proper format symbol and then use format:
import re
s = re.sub("_+", "{}", "I am ___ years old")
print(s.format(age))
If, as some suggested in comments, you might actually want the user to fill in the blank as they type, you can first print the line, then use \r and flush to go back to the beginning and then ask for the input, overwriting just as much so that the input cursor is on the ___ part.
print("I am ___ years old", end="\r", flush=True)
age = input("I am ")
print(age)
One more solution using console ANSI escape chars and module ansicon (needs once installing through python -m pip install ansicon), besides moving cursor it will also give nice things like coloring, etc. Escape chars thanks to this module will work both in Unix and Windows systems. Unix supports escape chars natively even without this module.
# Needs: python -m pip install
import ansicon
ansicon.load()
age = int(input('I am ___ years old' + '\x1b[D' * 13))
print('Your age is:', age)
Using escape chars many things can be done, e.g. coloring word years in green, using next line of code:
age = int(input('I am ___ \x1b[32myears\x1b[m old' + '\x1b[D' * 13))
which outputs:
Unix systems need no modules at all, thus code can be just two lines, this code you can see and try here online!
Color table for standard set of colors can be easily printed by next code, these numbers should be placed instead of 32 in code \x1b[32m above:
for first, last in [(30, 47), (90, 107)]:
for color in range(first, last + 1):
print(f'\x1b[{color}m{str(color).rjust(3)}\x1b[m ', end = '')
print()
which outputs:
This should solve your problem.
words_list= ["I","am","x","years","old"] # sentence having missing value as "x"
val = input("how many years old are you ?") # input the value of "x"
words_list[2] = val # replace the value of "x" at right place
print(' '.join(word for word in words_list)) # get the output with missing owrd at right place as sentence
user_input = ("how old are you ? : ")
print("you are ",user_input"," this old !")
This question already has an answer here:
How can I concatenate str and int objects?
(1 answer)
Closed 6 years ago.
I just started Automate The Boring Stuff, I'm at chapter 1.
myname = input()
print ('It is nice to meet you,' + myname)
lengthofname = len(myname)
print ('your name is this many letters:' + lengthofname)
I ran this, it gave me Can't convert 'int' object to str implicitly.
My reasoning at line 3 is that I want the variable myname to be converted into an integer and then plugged into line 4.
Why would this be an erroneous way of coding?
When you have print ('your name is this many letters:' + lengthofname), python is trying to add an integer to a string (which of course is impossible).
There are 3 ways to resolve this problem.
print ('your name is this many letters:' + str(lengthofname))
print ('your name is this many letters: ', lengthofname)
print ('your name is this many letters: {}'.format(lengthofname))
You have problem because + can add two numbers or concatenate two strings - and you have string + number so you have to convert number to string before you can concatenate two strings - string + str(number)
print('your name is this many letters:' + str(lengthofname))
But you can run print() with many arguments separated with comma - like in other functions - and then Python will automatically convert them to string before print() displays them.
print('your name is this many letters:', lengthofname)
You have only remeber that print will add space between arguments.
(you could say "comma adds space" but print does it.)
Your code seems to be Python 3.x. The following is the corrected code; just convert the lengthofname to string during print.
myname = input()
print ('It is nice to meet you,' + myname)
lengthofname = len(myname)
print ('your name is this many letters:' + str(lengthofname))
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," ")