How To Convert Python String To Int? – POFTUT

How To Convert Python String To Int?


Python has different variable types. Integer and string types are the most used types. And the conversation between them is required most of the time. In this post, we will look at howto convert string to int?

String Types

The string is character array-like text data. Following examples are all string

a="t" 
b="this" 
c="this too" 
d="1" 
e="1,5"

All of the above definitions are a string but they hold different or numeric characters. An integer is a base type for python. An integer is actually an umbrella definition.

Convert Single String Value to Integer

We will convert a single string variable value into an integer by using int function provided python.

d="1"    
i=int(d)

Type of the new variable can get with with type function.

Convert Single String Value to Integer
Convert Single String Value to Integer

Convert To Float

A string can be converted to float too. Float provides more precision on the numeric type. In this example, we will convert 1.5 into the float. As float provides floating numbers.

d="1.5" 
f=float(d)
Convert To Float
Convert To Float

Check Converted Number Type

We have already seen how to check the converted number types. But I just wanted to show this explicitly. Python programming language provides type() function which is used to check given variable type and print as type. In this example, we will check the type of variable str which is a string.

str="poftut.com" 
type(str)
Check Converted Number Type
Check Converted Number Type

LEARN MORE  What Is MATLAB SIMULINK?

1 thought on “How To Convert Python String To Int?”

Leave a Comment