Convert strings to integer types in Python

Share Your Love

Inside python strings are converted into integer types by using the built-in function int(). The int() function converts any python data type converts into an integer type. There are some different types of conversion like float() to convert float type. Now here we convert strings to integer types in Python.

Below is the list of possible ways to convert strings to integer types.

Syntax: int(string)

Example Of str To int:

num = '10'

# check and print type num variable
print(type(num))

# convert the num into string
converted_num = int(num)

# print type of converted_num
print(type(converted_num))

# We can check by doing some mathematical operations
print(converted_num + 20)

If you want to convert float() type then,

num = '10.5'

# check and print type num variable
print(type(num))

# convert the num into string
converted_num = float(num)

# print type of converted_num
print(type(converted_num))

# We can check by doing some mathematical operations
print(converted_num + 20.5)

Using float() function:

Here first convert to float, then convert float to integer.

Syntax: float(string)
a = '3'
b = '4'

# print the data type of a and b
print(type(a))
print(type(b))

# convert a using float
a = float(a)

# convert b using int
b = int(b)

# sum both integers
sum = a + b

# as strings and integers can't be added
# try testing the sum
print(sum)

Output:

class 'str'
class 'str'
7.0

Note: float values are in fractional form and here we use it.

Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.

Share Your Love
Default image
Lingaraj Senapati
Hey There! I am Lingaraj Senapati, the Co-founder of lingarajtechhub.com My skills are Freelance, Web Developer & Designer, Corporate Trainer, Digital Marketer & Youtuber.
Articles: 291

Newsletter Updates

Enter your email address below to subscribe to our newsletter