Python int to string format conversion
Introduction
Today, we are going to discuss how to convert numbers to strings and visa versa. It is a straightforward Python topic but it is important as well. There are various real life scenarios where type conversion is required. Before elaborating more, let us mention two example use cases to get a taste of what that means…
Reading numbers from file in python
Assume we have a text file (call it numbers.txt) where each line contains a number. For example…
1 2 3 4 |
1 7 3 4 |
We want to calculate the total sum of all numbers in the file. We can do that as follows…
1 2 3 4 5 6 |
sum = 0 with open("numbers.txt") as f: for line in f: sum = sum + int(line) # This should print 15 print(sum) |
In Python, reading lines from a text file produces a string data type. As you can see in the code snippet above, we had to convert the number in each line to integer so that we can compute the total sum. Let us take another example…
String int concatenation in python
Stitching strings and numbers together is a common use case in most programming language. For example, if we want to generate user ids from student names and numbers then we need to do the proper conversion. Here is an example…
1 2 3 4 5 |
student_name = "Mark" student_number = 1670 student_id = student_name + str(student_number) # This should print: Mark1670 print(student_id) |
In the code snippet above, we cannot simply concatenate a string to a number. The number has to be converted to a string first otherwise, an exception is raised. You can try it yourself by running the code snippet without any conversion. This brings us to the next section…
Dynamically vs statically typed languages
Python is a dynamically typed programming language. This means that we do not need to explicitly specify variable types. It is a convenient language feature but we should not be ignorant about it. The fact that Python interpreter detects variable types at runtime is true however if there is a type mismatch, an exception is raised. You might be wondering how on earth this is relevant to the main topic? Well, whenever we do type conversion (ex. subtracting two numbers in string format) we might encounter runtime errors due to type mismatch. Moral of the story, we must be careful when dealing with numbers and strings in Python. On the other hand, statically typed languages (ex. C++) would not approve any operation using incompatible types. The code does not even compile in the first place. The debate of which is better: a dynamically or statically typed language is beyond the scope of this article. Let us proceed with our discussion…
Conversion, casting and parsing
Since we are talking about type conversion, it would be relevant to point out that the terms casting and parsing refer to the same thing (i.e. conversion) one way or another.
- Type conversion in this article refers to Python built in functions required to convert between numbers and strings as we will demonstrate later
- Type casting (ex. languages like C++, Java, C#) is used to convert from one type to another. Here is an example in C++…
1 2 3 |
float x = 1.0; int y; y = (int) x; |
- In Javascript, the term parsing refers to converting a string to an integer. Here is an example in Javascript…
1 2 3 |
x = "101"; var num = Number.parseInt(x, 2); console.log (num); |
If you run the code snippet above, it should print 5 because 101 in binary mode is 5. That is enough of an introduciton, now it is time for Python type conversion…
Pyhon int to string
In Python, to convert from integer to string, we use the built in function str(integer)
- Returns a printable string representation of the provided integer
- If a string is provided instead of a number, str() returns the string itself
- If no argument is given, it returns an empty string
Let us take some examples…
Example 1
1 2 3 4 |
SSN = 188110551 print(type(SSN)) strSSN = str(SSN) print(type(strSSN)) |
The code snippet above should print the following output
1 2 |
<type 'int'> <type 'str'> |
Let us take another example using mismatched types…
Example 2
1 2 3 4 |
SSN = 188110551 Name = "John" ID = Name + SSN print(ID) |
This will raise an exception…
1 |
"TypeError: cannot concatenate "str" and "int" objects" |
To fix this problem…
1 2 3 4 5 |
SSN = 188110551 Name = "John" ID = Name + str(SSN) # This should print: John188110551 print(ID) |
We can also convert integers to strings using the backtick character and repr() function. Let us see how…
backtick character
Here is an example…
1 2 3 4 |
name = "Mark" grade = 4 # This should print: Mark4 print(name + `grade`) |
repr() function
repr() function is similar to str() in the sense that it converts integers to strings however they are not exactly the same. The distinction between the two needs a separate post so we will only mention the key difference here.
- str() is mainly used to convert an integer to a printable string
- repr() offers the same functionality but it is better for debugging and more magic
Here is an example…
1 2 3 4 |
name = "Mark" grade = 4 # This should print: Mark : 4 print (name + repr(grade)) |
Python float to string
Converting a float number into a string follows the same format as in the previous section. We just call the str(float) function. Here is an example…
1 2 3 4 5 6 7 8 9 10 11 12 |
# Given a list of shape:area pairs shapes = ["Triangle:4.0", "Rectangle:8.0", "Circle:10.0"] # We need to calculate total area sum = 0.0 for shape in shapes: item, area = shape.split(":") # Area is in string format so we need to # convert it to float because sum is also float sum = sum + float(area) # This should print: 22.0 print("Total area = {}".format(sum)) |
Python string to int
To do the opposite operation – converting a string to integer – we can use the built in function int(string)
- Returns an integer constructed from a string or 0 if no arguments are given
- The number can be an integer, long or float. If a float is provided then it is truncated to the nearest zero
- Base can be provided to indicate the numbering system. For example a base of 2 to indicate binary
Note that we are using a simplistic language here. To be more precise, in Python it is better to say object rather than number. For more details, it is advised to refer to the Python built in functions reference
Let us take an example…
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
# Student names and grades in string format student_records = ["John:90", "Mark:95", "Nathan:80"] # Total sum sum</span> = 0 # For each student do for student in student_records: # Split name and grade name, grade = student.split(":") # Recall grade is in string format # so we need to convert it to integer sum = sum + int(grade) # Compute average. Multiply by 1.0 to convert # the value to float avg = sum * 1.0/len(student_records) # This should print: 88.333 print("Average = {}".format(avg)) |
The default numbering system is decimal but the function int(string) accepts an optional base parameter as well. Let us see an example…
1 2 3 4 5 6 7 8 9 |
# Binary number in string format # This is equivalet to decimal 10 strbin = "1010" # Convert string to number using binary decimal = int(strbin, 2) # This should print: 10 print(decimal) |
Python string to float
The built in function float(string) returns a floating point number constructed from a number or string
- If the input is a string, it should contain a decimal number
- The sign is optional and has no effect if it is +
Here is some sample code…
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
# This should print: 1.5 # The positive sign is optional print(float('+1.5')) # This should print: -12.0 # White space and new line # wont make any difference print(float(' -12\n')) # This should print 0.01 # You can use e or E for exponential print(float('1e-02')) # This should print 10000.0 print(float('+1E4')) # This prints -inf print(float('-Infinity’)) |
Misc notes
When performing number and string type conversions in Python, we need to be aware of the following scenarios…
- The addition sign (+) is used to concatenate strings as well as add numbers. So mixing numbers and strings without proper conversion will raise run time exceptions. We provided an example earlier on this case
- Converting a string with decimal places into integer raises an exception. Here is an example…
1 2 |
x = "1.0" y = int(x) |
If you run the code snippet above, you should get the following exception
1 |
ValueError: invalid literal for int() with base 10: '1.0' |
- Converting a string to integer on the fly raises an exception. It cannot be done in one statement due to language design decision. Here is an example…
1 2 3 4 5 |
# This should work fine print int(float(x)) # This should fail # ValueError: invalid literal for int() print int(x) |
- Pay attention to character encoding when dealing with strings. This topic is beyond the scope of this article but it is super important to be aware of that
That is all for today, let us summarize…
Summary
- Converting numbers to strings or visa versa has many applications. To mention a few: reading numbers from file and string number concatenation
- Remember that Python is a dynamically typed language which means variable types are not explicitly specified. For that reason, one has to be careful when doing type conversion specially in the case of type mismatch as it will raise runtime exceptions
- Type conversion, casting and parsing numbers are different ways to refer to type conversions
- Python provides the built in function str(number) to convert from integer or float to string
- Python provides the built in function int(string) to convert from string to integer
- Python provides the built in function float(string) to convert from string to float
References
Thanks for visiting. Please leave a comment if you have a question.