I was trying to concatenate a string and a number in Python. It gave me an error when I tried this:
"abc" + 9
The error is:
Traceback (most recent call last): File "<pyshell#5>", line 1, in <module> "abc" + 9 TypeError: cannot concatenate 'str' and 'int' objects
Why I am not able to do this?
How can I concatenate a string and a number in Python?
If you want to concatenate a string and a number, such as an integer int or a floating point float , convert the number to a string with str() and then use the + operator or += operator.
To concatenate a string to an int value, use the concatenation operator. Here is our int. int val = 3; Now, to concatenate a string, you need to declare a string and use the + operator.
The answer to your question is "no". A number can have one of several C types (e.g. int , double , ...), but only one of them, and string is not a numeric type.
Python is strongly typed. There are no implicit type conversions.
You have to do one of these:
"asd%d" % 9 "asd" + str(9)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With