Pythonで変数の型を変更する方法/int、float、str関数の使い方

IT

Pythonで変数の型を変更したい場合は、変数の型名の後ろに()を付けた関数で元の関数を変換できます。

スポンサーリンク

変数の型変更の例

整数型に変換
int()

浮動小数点数型に変換
float()

文字列型に変換
str()

python 型変換1
簡易的な例として、int型の変数をfloat型に変換してみます。
python 型変換2
float()に変数を入れただけだと、元の変数の型自体を変更していない点に注意してください。
#python
var = 1
print(type(float(var)))
たとえばこの場合、type関数の中に入れた変数をさらにfloatで包むことで、
python 型変換3
floatに変換した値を出力することができます。
#python
var = 1
var = float(var)
print(type(var))
よって変数の型を変更したい場合、変数に型を変えた変数を代入することで実現できます。
Python操作方法、関数・メソッドリファレンス
使用用途別にまとめたPythonリファレンスページです。 初期準備、基本概念 ダウンロード、インストール、起動 ShellとEditor、保存、実行 保存したPythonの起動 コメント、docstring、行またぎ コメント、...

コメント

This website stores cookies on your computer. These cookies are used to provide a more personalized experience and to track your whereabouts around our website in compliance with the European General Data Protection Regulation. If you decide to to opt-out of any future tracking, a cookie will be setup in your browser to remember this choice for one year.

Accept or Deny