Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

python

How to convert float to string in Python

Shahpar Khan

Datatypes

In some languages, the developer needs to explicitly specify the datatype. For example, in C++, variables are declared by first specifying the datatype and then following it with the variable name:

int my_int;
float my_float;
string my_string;

On the other hand, in languages like JavaScript or Python, there is no need to explicitly mention a variable’s datatype at the time of declaration as the datatype is set according to the value assigned to it.

#JavaScript
var my_int = 123
var my_float = 123.123
var my_string = "123"

#Python
my_int = 123
my_float = 123.123
my_string = "123"

Later, after the variable’s initial declaration, it can be type-casted in a different datatype. Type-casting comes in handy when avoiding ambiguous comparisons between different data types and operators/functions performing unexpectedly.

######## FAULTY COMPARISON ########

my_float = 123.123
my_string = "123.123"

equal = (my_float == my_string)

if equal:
  print("Variables are equal")

else:
  print("Variables are not equal")

######## UNEXPECTED FUNCTIONALITY ########

#Want to concatenate 123.0 and string "my float is: "

#Throws an error 

my_float = 123.0
my_string = "my float is: " 

result = my_string + my_float

print(result)
Possible errors

To deal with such scenarios, we can easily convert datatypes in Python using type-casting:

Syntax Description
str() Cast to string
float() Cast to float
int() Cast to int

To check the type of a variable, use the type() method.

In the code snippet below, observe how we can avoid the error in the previous example by type-casting float to string in Python:

#Want to concatenate 123.0 and string "my float is: "

my_float = 123.0
my_string = "my float is: " 

result = my_string + str(my_float)

print(result)
Casting float to string

RELATED TAGS

python

CONTRIBUTOR

Shahpar Khan
Copyright ©2022 Educative, Inc. All rights reserved
RELATED COURSES

View all Courses

Keep Exploring