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))
Related
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
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 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 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"+"!")
# This program says hello and asks for my name.
print('Hello world!')
print('What is your name?')
myName = input()
for Name in myName (1,10):
print('It is nice to meet you, ' + myName)
I was asked to create a program that uses a for loop and another program for while loop, I've got this for for loop but I'm trying to set how many times I want it to repeat myName. Please help me out if you can, thanks in advance!
# your code goes here
print('Hello world!')
print('What is your name?')
#I use raw_input() to read input instead
myName = raw_input()
#ask user how many times you would like to print the name
print('How many times would you like your name to repeat?')
#raw_input() reads as a string, so you must convert to int by using int()
counter = int(raw_input())
#your main issue is here
#you have to use the range() function to go a certain length for for-loops in Python
for x in range(counter):
print('It is nice to meet you, ' + myName)
Note: For your code, you should use input() instead of raw_input(). I only used raw_input() because I have an outdated compiler/interpreter.
python 3.x (3.5)
#Just the hello world
print('Hello world!')
#use input() to let the user assign a value to a variable named myName
myName = input('What is your name?:')
#now let the user assign an integer value to the variable counter for how many times their name should be repeated. Here i am enclosing the input of the user with an int() to tell python that the data type is an integer
counter = int(input('how many times do you want to repeat your name?:'))
#Use the Range function to repeat the names
for a in range(counter):
print('It is nice to meet you, ' + myName)
for Name in myName (1,10):
print('It is nice to meet you, ' + myName)
myName is a string, so you won’t be able to call it, which is what the parentheses do. If you want to repeat the name for a certain amount of times, you should iterate over a range:
for i in range(10):
print('It is nice to meet you, ' + myName)
This will print out the greeting 10 times.