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…

We want to calculate the total sum of all numbers in the file. We can do that as follows…

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…

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++…

  • In Javascript, the term parsing refers to converting a string to an integer. Here is an example in Javascript…

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

The code snippet above should print the following output

Let us take another example using mismatched types…

Example 2

This will raise an exception…

To fix this problem…

We can also convert integers to strings using the backtick character and repr() function. Let us see how…

backtick character

Here is an example…

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…

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…

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…

The default numbering system is decimal but the function int(string) accepts an optional base parameter as well. Let us see an example…

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…

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…

If you run the code snippet above, you should get the following exception

  • 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…

  • 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.

Tags:

Add a Comment

Your email address will not be published. Required fields are marked *