Python

Python String to Int Example

1. Introduction

For me there is something beautiful about code. I like to think of it as “Digital Alchemy”. A very wise programmer once told me that the the “code never lies”. Oh how true that is. Coding can be brutal, humbling and it can also be incredibly rewarding.

We all have our favourite programming languages. For whatever different reasons. Discussing which language is better often results in heated debate. You may as well be discussing religion or politics. One of my favourite languages is Python. In this article we are going to take a look at converting a String to an integer in Python.

2. The History of Python

Guido van Rossum created Python in the late 80’s. It was first officially released in 1991. The name python has nothing to do with the snake, but rather it was a nod by Van Rossum to Monty Python’s “Flying Circus“.

He was given the title “Benevolent Dictator for Life” by the Python community. Essentially this means that he had the “final say” and could veto any proposals regarding the language. Van Rossum attributes the vibrant community involvement to the language being really simple:

Well, that’s because it’s such a simple language. There’s only one thing that really stands out, and that’s the indentation. Apart from that, syntactically it’s really boring, which means that everybody who is in the least bit interested in improving the language can easily imagine themselves to be a language designer too, because there’s not a whole lot of magic in there. Even if you are in fact clueless about language design you can tell that Python is a very simple language.

https://web.archive.org/web/20061001143603/http://www.linuxformat.co.uk/modules.php?op=modload&name=Sections&file=index&req=viewarticle&artid=10

In March 2001 the “Python Software Foundation” (PSF) was launched:

The mission of the Python Software Foundation is to promote, protect, and advance the Python programming language, and to support and facilitate the growth of a diverse and international community of Python programmers.

https://www.python.org/psf/

In July 2018 Guido van Rossum stepped down as BDFL and relinquished control of the language.

3. Why use Python?

Personally, I like Python because it is relatively easy to learn and I think it is an elegant language. For anyone looking to get into programming I would strongly recommend Python as your first language. Python can be found pretty much everywhere nowadays. In fact python is found in a number of operating systems as part of the core libraries.

Python is well supported by the PSF and it has tons of libraries available to assist with just about any programming paradigm. Whether it’s web programming, desktop, machine learning or artificial intelligence, there are always numerous Python tools and frameworks available to assist you the programmer.

That been said, Python like any language has its drawbacks and critics. Backward compatibility is an issue and “speed” is another often cited drawback. The latter in my opinion is relative. Any badly written code will arguably perform poorly and there are a number of enhancements that have sped things up in the Python arena.

Python Virtual Environments are a great way to get the required version up and running without impacting system libs. So this could help with implementing the version of your choice. On the speed front there are a number of enhancements available. PyPy is one example that implements efficiencies using things like “Just in Time” (JIT) compilation. Again for every issue, real or assumed there would seem to be a solution in Python land.

4. Let’s get to it!!!

4.1 Versions

First we need to setup our Python development environment. I’m running on Mac and have Python 2.7 preinstalled. I want to use Python 3 for this and so I could install a virtual environment which uses version 3 or I can simply install is alongside the preinstalled version and invoke it with python3. I have both versions installed on my machine. First type python –version at the command prompt to see which version (if any) is installed.

Python String to Int - Check the versions
Check the versions

4.2 Virtual Environments

Ok so I’m good to go for either version, but let’s take this opportunity to discuss Python virtual environments. If you want to isolate a specific project and its dependencies, then virtual environments are the way to go. I recommend Pipenv. https://pipenv.readthedocs.io/en/latest/

Pipenv is a way of dealing with pip and virtualenv together. There is a great “Playground” available, so you can test it in browser without installing anything: https://rootnroll.com/d/pipenv/

Seeing as this is just a simple tutorial and not a project that requires isolation from a dependancies perspective, I am just going to use Python 3.7 which is installed on my Mac already.

5. Python converting string to int

As I said, python is (for me at least) all about elegance and simplicity. Let’s use the interactive Python shell to convert a String to an integer

5.1 An interactive example

For a much better understanding of the Python shell, please see this link: https://www.python.org/shell/

I often find myself using the shell for prototypes and the like and once you get the hang of it it’s a great tool to add to your programming arsenal.

Python String to Int - interactive shell example
An interactive shell example

5.2 Getting classy…..

While that demonstrates the objective of the exercise, it’s just in the shell and not as a standalone Python class. There is also a lot more information regarding the int() function here: https://docs.python.org/3/library/functions.html#int

In Python the int() function is in fact an Object cast: int(), str() and float() are just some of the examples. Have a look at the link and let’s create a class next. Something a little more polished with some added functionality.

StringToInt.py

class StringToInt:

	def __init__(self, string, int):
		self.string_integer = string;
		self.int_integer = int;

#strToIntFunction 
	def strToIntFunction(self):
		print("The strToIntFunction assigns the string_integer value to int_integer: ")
		self.int_integer = int(self.string_integer)
		print(self.int_integer)




sti = StringToInt("20", 100)

print("The value of string_integer: " )
print(sti.string_integer)
print("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@")
print("The value of int_integer: ")
print(sti.int_integer)
 

The code above is a very simple example of how to convert a string to an integer in python. I added a function just to show how it can be instantiated and I think it shows a more practical application for a “real world” scenario.

Let’s take a look at the output by running it:

python3 StringToInt.py

StringToInt.py output

There you have it, the string successfully cast to an integer. Oh, but you ask how can we be sure? Python to the rescue with the handy type() function! See the below code:

StringToInt.py

#now let's make 100% sure that the original string is an integer
print("Confirm the 'type' of the int_integer variable")
print ("using type() method\n") 
print (type(sti.int_integer)) 

Edit your class and add the snippet above. Now let’s run it again using:

python3 StringToInt.py

int type confirmed.

Ok, so what just happened there? Python provides us with a type() method to see exactly what class a certain variable is. As you can see type(sti.int_integer) returned:

Take a look at this link: https://www.w3schools.com/python/ref_func_type.asp for more information about the type() function.

The final class should look like this:

StringToInt.py

class StringToInt:

	def __init__(self, string, int):
		self.string_integer = string;
		self.int_integer = int;

#strToIntFunction 
	def strToIntFunction(self):
		print("The strToIntFunction assigns the string_integer value to int_integer: ")
		self.int_integer = int(self.string_integer)
		print(self.int_integer)




sti = StringToInt("20", 100)

print("The value of string_integer: " )
print(sti.string_integer)
print("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@")
print("The value of int_integer: ")
print(sti.int_integer)

#now let's make 100% sure that the original string value is an integer
print("Confirm the 'type' of the int_integer variable")
print ("using type() method\n") 
print (type(sti.int_integer)) 

6. Conclusion

So there we have it. A very simple example of converting a string to an int in Python. I must say every time I tinker with Python (and it’s been a while) I am always struck by it’s simplicity and ease of use. So whether it’s for simple scripting and administrative tasks or for a complete enterprise solution, I really recommend at least considering Python as an option. There are tons of third party libraries and fantastic frameworks out there that are both well supported and documented.

7. Download the Source Code

This was an example of string to int conversion in python.

Download
You can download the full source code of this example here: Python String to Int Example

Ed de Jongh

Ed has worked in the IT industry for over 20 years, gaining experience in programming, architecture and design. As a seasoned Solution Architect, he is passionate about advancing simplicity and elegance. In addition to solution design, he is also involved in development and integration. Outside of the office, enjoys anything on two wheels and being a dad.
Subscribe
Notify of
guest

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

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button