environment windows7 (I want a Mac Book Pro 16inch) Visual Studio Code chrome python ver3.8.3
This article is written for beginners in programming and Python.
str integer was a number (integer) and string was a character (string). If you try to output a number (integer) by concatenating it with a character (character string) as it is, it will be as follows.
style.py
calc = 100 * 3.14
answer = "100 times the circumference" + calc + "is"
print(answer)
#answer = "100 times the circumference" + calc + "is"
#TypeError: can only concatenate str (not "float") to str
I got an error.
TypeError:can only concatenate str (not "float") to str
This error is the error "Cannot concatenate because the type is different".
Since the sentence "100 times the pi is" and the sentence "is" is a character (string) and the variable calc is a number (although it is a floating point number)
"Let's arrange characters (character strings) and numbers (integers and floating point numbers) before concatenating them."
It is a promise.
In such a case, enclose the character (character string) as it is in "" and convert the number (integer, floating point number) to the character (character string).
Then, should I enclose it in Calc
with" "?
type.py
calc = 100 * 3.14
answer = "100 times the circumference" + "calc" + "is"
print(answer)
#100 times the circumference is calc
I have recognized calc
as a character (character string) as it is.
Let's change it as follows.
This is where the theme str
comes into play.
style.py
calc = 100 * 3.14
answer = "100 times the circumference" + str(calc) + "is"
print(answer)
#100 times the circumference is 314.0
Yes, it was output successfully.
What's different about the above two codes is
answer = "100 times the pi is" + calc
+" "
answer = "100 times the pi is" + str (calc)
+ ""
And just added str () to calc.
Use str ()
to arrange (convert) numbers (integers, floating point numbers) into characters (strings).
The above example uses variables, but the simpler one is easier to understand.
type.py
print(type(123))
#<class 'int'>
print(type(str(123)))
#<class 'str'>
The upper part of the above example is 123 Is a number (integer) I'm saying. The bottom row is str(123) Is a character (character string) I'm saying.
This is how to convert type: str
.
Recommended Posts