• Home
• Blog
• Python
• Quick Python tip: “int” strips strings of whitespace

# Quick Python tip: “int” strips strings of whitespace

November 3, 2019 . By Reuven

Let’s say you’re writing a Python program that asks the user to enter a number, so that you can double it:

```>>> n = input("Enter a number: ")
Enter a number:```

Just doubling what we get is a bad idea, though. If the user enters “123”, then we’ll get this:

`>>> print(n*2)123123`

What’s going on? The “input” function always returns a string. The trailing newline character is removed, but we’re always going to get a string. If we multiply a Python string by 2, we get a new string back â€” a doubled version of what the user entered.

The obvious solution would be to use “int” to convert the string. For example, we could do this:

`>>> print(int(n)*2)246`

But wait: What if the user enters extra whitespace on either side? That is, what if they do this:

```>>> n = input("Enter a number: ")
Enter a number:         123        ```

You can see that there are extra space characters on either side of the ‘123’, and it becomes even clearer if we do this:

```>>> print(f'"{n}"')
"       123       "
>>> print(len(n))
17```

To avoid potential problems, you might want to use “str.strip”, a great method that (by default) removes all whitespace (i.e., space, tab, newline, carriage return, and vertical tab) from the edges of the string. In other words:

```>>> print(int(n.strip())*2)
246```

Sure enough, this will work, removing any whitespace characters from the ends of “n”. But guess what: It’s not necessary! That’s because Python’s “int” class automatically strips whitespace on any string it gets as input:

```>>> int('5')
5
>>> int('   5    ')
5
>>> int('\n\n\t\t  5\t\t\v\v\t\t\n\r')
5```

This is true, even though the str.isdigit/str.isnumeric/str.isdecimal methods will return “False” if you apply them to a string containing whitespace.

But be careful: If you apply “int” to the empty string, you’ll get a “TypeError” exception. And if you call “int” without any arguments, you’ll get the integer 0 back.

So save a few seconds when you convert strings to integers, and don’t bother stripping them first! You can rely on “int” to do it for you.

Related Posts

## Level up your Python skills this August

Level up your Python skills this August

## Prepare yourself for a better career, with my new Python learning memberships

Prepare yourself for a better career, with my new Python learning memberships

## I’m banned for life from advertising on Meta. Because I teach Python.

I’m banned for life from advertising on Meta. Because I teach Python.
• Pete says:

“The training newline character” was likely meant to be “The trailing newline character”

• reuven says:

Ha! I’m so used to writing the word “training” that I didn’t even notice. Thanks!

• NaVeeN says:

So, we can use int directly on a string even it contains a whitespace without striping it, right?

• reuven says:

Precisely, yes.