AppDividend
Latest Code Tutorials

# How to Convert Python String to Int

An integer can be stored using different data types. For example, two possible Python data types for representing the integer are the following.

1. Integer
2. String

Let’s represent an integer using a string literal. See the following code.

```# app.py

v1 = "1"
v2 = "11"

print('The value of v1 is: ', v1)
print('The data type of v1 is:', type(v1))
print('The value of v2 is: ', v2)
print('The value of v2 is: ', type(v2))
```

#### Output

```python3 app.py
The value of v1 is:  1
The data type of v1 is: <class 'str'>
The value of v2 is:  11
The value of v2 is:  <class 'str'>```

The Python interpreter understands that you want to store the integers 1 and 11 as strings.

Python str() is a standard inbuilt function to convert the integer to string value.

You call it with the String containing the number as the argument, and it returns the number converted to an integer.

## Python String to Int

To convert Python string to int, use the int() function. The int() is a built-in function that accepts the initial string and the optional base representing the data as arguments and returns an integer.

```str = "1921"
print(type(str))
print("After converting Python String to Integer")
integer = int(str)
print(integer)
print(type(integer))```

#### Output

```<class 'str'>
After converting Python String to Integer
1921
<class 'int'>```

You can see from the output that we have successfully converted a string to an integer in Python.

Let’s see how to convert back to String from integer.

To store an integer value as an int in Python, assign a number to any variable, and it will become an integer data type. Of course, you can also use the String literal to store an integer.

If you define k = “10,” Python understands that you want to store the integer 10 as a string.

Although there are numerous other number systems, such as binary and hexadecimal, which use different bases to represent an integer.

For instance, you can represent the number one hundred and ten(110) in binary and hexadecimal as 1101110 and 6e, respectively.

## Python different number data types

1. int (signed integers) − They are often called just ints or integers, are positive or negative whole numbers with no decimal point.

2. long (long integers ) − Also called longs, they are integers of unlimited size, written like integers and followed by the uppercase or lowercase L.
3. float (floating point real values) − Also called floats, represent real numbers and are written with the decimal point dividing the integer and fractional parts. Floats may also be in scientific notation, with E or e indicating the power of 10 (2.5e2 = 2.5 x 102 = 250).
4. complex (complex numbers) − are of the form a + bJ, where a and b are floats, and J (or j) represents the square root of -1 (which is an imaginary number). The real part of the number is a, and the imaginary part is b. Complex numbers are not used much in Python programming.

## Convert Python String to Int with different bases

You have to keep in mind many factors and bases while converting from one format to another format. For example, if you have the decimal integer represented as a string and need to convert the Python string to an int, you pass the String to the int() method, which returns a decimal integer.

If you are looking for a solution to converting Python string to int and int to string, you will find your answer in this post.

By the end of this tutorial, you’ll understand:

1. How to convert Python string to int.
2. How to parse Python str to int in a different base.
3. How to convert Python str to int with commas.

Python defines type conversion functions to convert one data type to another, useful in day-to-day and competitive programming.

We can use the type function to get the data type of any variable.

See the following example.

```# app.py

amp = '123'
print(type(amp))

eli = 'The Computer Guy'
print(type(eli))

num = 1234
print(type(num))

ser = [1, 2, 4]
print(type(ser))

dict = {1: 'Android', 2: 'iOS', 3: 'Symbian'}
print(type(dict))```

We have taken the different types of variables and printed them on the Python Console. See the following output.

Like the str() inbuilt, Python also offers a handy built-in, which takes a String object as an argument and returns the corresponding integer object.

If you want to convert the number represented in a string to int, you must use the int() function. See the following example.

```# app.py

amp = '123'
print(type(amp))

convertedInt = int(amp)
print(type(convertedInt))
print(convertedInt)```

See the below output.

We have converted the String to Integer in Python.

Integers are whole numbers. In other words, they have no fractional component. You can use two data types to store an integer in Python: int and str.

These types offer flexibility for working with integers in different circumstances.

In this tutorial, you’ll learn how to convert a Python string to an int. You’ll also learn how to convert an int to a string.

So, this is the same as python string to int.

```#app.py

eleven = "11"
print(eleven)
# Converting string to number
millie = int(eleven)
print(millie)
```

See the output.

```➜  pyt python3 app.py
11
11
➜  pyt
```

## Converting str to int from different base

Strings can be transformed into numbers using the int() and float() methods. If your String does not have decimal places, you will probably want to convert it to an integer using the int() method.

If the String you want to convert into int belongs to a different number base other than base 10, you can specify that base for that conversion.

But one thing you need to keep in mind is that the output integer is always in base 10.

Another thing you need to remember is that a given base must be between 2 to 32. See the following example.

```# app.py

amp = '123'
print(type(amp))

convertedInt = int(amp)
print(type(convertedInt))
print(convertedInt)

convertedInt8 = int(amp, base=8)
print(type(convertedInt))
print(convertedInt)

convertedInt16 = int(amp, base=16)
print(type(convertedInt16))
print(convertedInt16)

convertedInt32 = int(amp, base=32)
print(type(convertedInt32))
print(convertedInt32)```

See the below output.

While converting from String to int, you may get a ValueError exception. The ValueError exception occurs if the String you want to convert does not represent any numbers.

If you’re going to convert the hexadecimal number to an integer, you will not have to pass the argument base=16 in the int() function.

It will raise the ValueError exception if any digit does not belong to a decimal number system.

You should remember some of the exceptional cases:

1. As an argument, the floating-point(an integer with a fractional part) will return the float rounded down to the nearest whole integer. For example: print(int(11.21)) will print 7. Also, print(int(“11.21”))  will result in the Error since the String is an invalid argument to convert to an integer.

``````Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: '11.21'``````
2. Also, any integer in words, if given as the argument, will return the same error as above: print(int(“eleven”))  will provide an error as follows.

``````Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: 'eleven'``````

The int() function assumes that the string argument represents the decimal integer by default. If, however, you pass the hexadecimal String to int() method, then you’ll see the ValueError.

See the following code.

```# app.py

v1 = "0x11E"

print('The value of v1 is: ', v1)
print('The data type of v1 is:', type(v1))

conv = int(v1)
print(conv)```

#### Output

```python3 app.py
The value of v1 is:  0x11E
The data type of v1 is: <class 'str'>
Traceback (most recent call last):
File "app.py", line 6, in <module>
conv = int(v1)
ValueError: invalid literal for int() with base 10: '0x11E'```

The error message suggests that the String is not a valid decimal integer.

It’s essential to recognize the difference between two types of failed results of passing the String to int():

1. Syntax Error: A ValueError will be thrown when the int() function doesn’t know how to parse the String using a provided base (10 by default).
2. Logical Error: The int() function does know how to parse a String, but not the way you expected.

## Parse int to string in Python

We can use the inbuilt str() function to parse Python int to String to convert an integer to String.

Parsing is the same as converting in programming.

See the following example.

```# app.py

hexValue = 0x2f22
print(hexValue)
print(type(hexValue))
hexValue = str(hexValue)
print(hexValue)
print(type(hexValue))```

See the output below.

See another example of Int to String conversion in Python.

```# app.py

digit = 1921
print(digit)
print(type(digit))
digit = str(digit)
print(digit)
print(type(digit))```

## Python string to float

To convert a string to float in Python, use the float() function. The float() is a built-in Python method that coerces the string value to an integer. You may use a floating class for converting the decimal String to a float number.

See the following example for a demonstration.

```# app.py

eleven = '11.21'
hopper = 19.21

el = float(eleven) + hopper
print ("The value of el = ",el)
```

See the following output.

```➜ pyt python3 app.py
The value of el = 30.42
➜ pyt
```

For more information, check out converting String to Float in Python example.

## Converting string numbers in a list to integers

If you intend to convert the string numbers in the Python list, then one way to convert those strings into an int is to use a list comprehension. As shown in the example below, a new list will be created to use the int in each iteration.

```# app.py

str_list = ['11', '19', '21']
int_list = [int(a) for a in str_list]
print (int_list)
```

See the following output.

```➜  pyt python3 app.py
[11, 19, 21]
➜  pyt
```

## Converting String to int with commas

What about string numbers with commas like “11,000,000”. If you try to convert this String using an int or float, it will generate the Error because of the commas.

The solution to the above Error is by importing the locale.

```import locale
```

Now, you can use the USA locale setting like the following.

```locale.setlocale( locale.LC_ALL, "en_US.UTF-8")
```

However, this may cause problems with different locations.

So, one other solution is to replace the comma with nothing. For example, see the code below.

```# app.py

elevenmillion = '11,000,000'
eleven = int(elevenmillion.replace(',',''))

print ("The integer value", eleven)
```

See the following output.

```➜  pyt python3 app.py
The integer value 11000000
➜  pyt
```

## Python int to String

To convert Python integer to string, use the built-in str() function. The str() is a built-in Python function that takes any data type and converts it into a string, including integers, and returns a string.

See the following code.

```# app.py

v1 = 1
v2 = 11

print('The value of v1 is: ', v1)
print('The data type of v1 is:', type(v1))
print('The value of v2 is: ', v2)
print('The value of v2 is: ', type(v2))
```

#### Output

```python3 app.py
The value of v1 is:  1
The data type of v1 is: <class 'int'>
The value of v2 is:  11
The value of v2 is:  <class 'int'>```

If you want to get the data type of any value, use the type() function.

## Conclusion

Strings can be converted to numbers using the int() and float() functions. If the String does not have decimal places, convert it to an integer using the int() method. The str() function is used to convert the integer to String.

The ord() function converts the character to an integer.

The hex() function converts an integer to a hexadecimal string.

The oct() function converts an integer to the octal String.

That is it for the tutorial.

## Recommended Posts

Python float()

Python String to List

Python data types

1 Comment
1. Hiral says

Thanks for posting, this article was very helpful when converting string to int and vice versa. I came across a similar post though it was certainly not quite as thorough as this!

Thanks again,

This site uses Akismet to reduce spam. Learn how your comment data is processed.