Refer to a basic atoi in C:

int myAtoi(char *str)
{
    int res = 0; // Initialize result

    // Iterate through all characters of input string and update result
    for (int i = 0; str[i] != '\0'; ++i)
        res = res*10 + str[i] - '0';

    // return result.
    return res;
}

Which translates into the Python:

def atoi(s):
    rtr=0
    for c in s:
        rtr=rtr*10 + ord(c) - ord('0')

    return rtr

Test it:

>>> atoi('123456789')
123456789   

If you want to accommodate an optional sign and whitespace the way that int does:

def atoi(s):
    rtr, sign=0, 1
    s=s.strip()
    if s[0] in '+-':
        sc, s=s[0], s[1:]
        if sc=='-':
            sign=-1

    for c in s:
        rtr=rtr*10 + ord(c) - ord('0')

    return sign*rtr

Now add exceptions and you are there!

Answer from dawg on Stack Overflow
🌐
freeCodeCamp
freecodecamp.org › news › python-convert-string-to-int-how-to-cast-a-string-in-python
Python Convert String to Int – How to Cast a String in Python
November 29, 2021 - fave_number = 7 #7 is an int #"7" would not be an int but a string, despite it being a number. #This is because of the quotation marks surrounding it · Sometimes when you're storing data, or when you receive input from a user in one type, you'll need to manipulate and perform different kinds of operations on that data. Since each data type can be manipulated in different ways, this often means that you'll need to convert it.
🌐
Real Python
realpython.com › convert-python-string-to-int
How to Convert a Python String to int – Real Python
January 16, 2021 - There are several ways to represent integers in Python. In this quick and practical tutorial, you'll learn how you can store integers using int and str as well as how you can convert a Python string to an int and vice versa.
🌐
Reddit
reddit.com › r/learnpython › (python) convert sting of a number into an integer
r/learnpython on Reddit: (Python) Convert Sting of a Number into an Integer
May 14, 2022 -

I want to convert a sting of a single number, for example ['14'] into just 14. I tried all kinds of replace functions to separate just the number, but they all end up as an error. Any help is greatly appreciated!

Top answer
1 of 2
1
This is just two steps: get the string from the list, and parse the string as a number. If you needed to get the first element of a list, how would you do it? If you needed to parse a string and an integer, how would you do it? Those phrases can be searched for.
2 of 2
1
Okay, I think I may know what's going on from what you've said. Is the string you are trying to convert from this: "14" or this: "['14']"? If you have a string that looks like this: "['a', 'b', 'c']" then it sounds like you probably called the string() method on a LIST object and not the integer itself. Let's say you have a list of strings that looks like this: string_list = ['1', '2', '3'] Note that string_list is NOT itself a string. It is a list that holds string values. Now, if you tried to convert this list to an integer by calling int(string_list), you would get an error, since there isn't really a way to convert a list to a single integer value. If you wanted to call int() on a number inside of the list, instead of the list itself, you need to access it first. There are a ton of ways of doing this, but the simplest way is by using indexing. After a list, or any other container object, place two square brackets with the index you want to access (0 is the first element, 1 is the second element, etc.) It will look like this: list_object[index]. You still have to do this, even if there is only a single element in your list, like your example of ['14']. Now, let's go back to our example with string_list. If we want to turn the "1" from a string into an integer, we do it like this: number_as_string = string_list[0] number_as_int = int(number_as_string) assert type(number_as_int) == 'int' So, in your example, to convert ['14'] into just the integer 14, assuming the list object is stored in a variable called string_number_list you would call int(string_number_list[0]
Top answer
1 of 3
4

Doctstrings

The docstring:

"""
Convert numeric string to number withoutusing python's built in functions.
"""

Should be at the top of the inside of the function.

(Also withoutusing should be without using.)

Global Variables

Global variables are typically a bad design practice. Move these:

dec_places = {6:100000, 5:10000, 4:1000, 3:100, 2:10, 1:1}
char_digit = {'0':0, '1':1, '2':2, '3':3, '4':4, '5':5,  '6':6, '7':7, '8':8,  '9':9}

Inside the function.

Function naming

str2int should be renamed to str_to_int.

Better algorithm

dec_places is unneeded and limits your algorithm significantly.

I would enumerate over the reversed of your string:

for ind, char in enumerate(reversed(num_str)):
    number += char_digit[char] * 10**(ind + 1)

enumerate takes an iterable and creates tuples of (0, el1), (1, el2) ....

We reverse the string and then multiply each character by the appropriate power of 10. This allows you to go beyond the 6th power.

Alternatively, you can keep an iter value that counts up from 1. I'll leave this as an exercise. It might be faster than using reversed. You should not need a dictionary though.

2 of 3
3

You should avoid using iter as a variable name, since it happens to be the name of a built-in function. It's confusing to other Python programmers who have to read your code, and could produce a failure if you ever want to call the standard iter() function.

In any case, you don't want to have a clumsy loop that is based on char and also maintains iter. You certainly don't want an algorithm that puts an upper bound on the numbers you can handle. The standard algorithm goes like this:

CHAR_DIGIT = {'0':0, '1':1, '2':2, '3':3, '4':4, '5':5,  '6':6, '7':7, '8':8, '9':9}

def str2int(num_str):
    """
    Convert numeric string to number without using Python's built in functions.
    """
    number = 0
    for char in num_str:
        number = 10 * number + CHAR_DIGIT[char]
    return number
🌐
Cherry Servers
cherryservers.com › home › blog › cloud computing › how to convert string to int in python | comprehensive guide
How to Convert String to int in Python? | Cherry Servers
November 7, 2025 - This is a good option if you need to dynamically evaluate Python expressions. When you pass a string argument to eval(), it compiles it into bytecode and evaluates it as a Python expression. Essentially, the eval() function allows you to convert strings to integers.
Find elsewhere
🌐
DigitalOcean
digitalocean.com › community › tutorials › python-string-to-int-int-to-string
Python String to Int, Int to String | DigitalOcean
August 4, 2022 - In this tutorial, we will learn how to convert python String to int and int to String in python.
🌐
DigitalOcean
digitalocean.com › community › tutorials › how-to-convert-data-types-in-python-3
How To Convert Data Types in Python 3 | DigitalOcean
August 20, 2021 - Let’s first look at converting integers. To convert the integer 12 to a string value, you can pass 12 into the str() method: ... When running str(12) in the Python interactive shell with the python command in a terminal window, you’ll receive the following output:
🌐
Kanaries
docs.kanaries.net › topics › Python › covnert-string-to-int-python
How to Convert String to Int in Python: Easy Guide – Kanaries
In this essay, we will explore type casting, built-in functions, and error-handling techniques to effectively convert strings to integers in Python.
🌐
GeeksforGeeks
geeksforgeeks.org › python › convert-string-to-integer-in-python
Convert String to Int in Python - GeeksforGeeks
The simplest way to convert a string to an integer in Python is by using the int() function.
Published   September 11, 2025
🌐
iO Flood
ioflood.com › blog › python-string-to-int-conversion-guide-with-examples
Python String to Int Conversion Guide (With Examples)
November 23, 2023 - This is where Python’s error handling mechanisms, like try/except blocks, prove their worth. Here’s an example of attempting a conversion and handling any errors that arise: try: number_string = '123.45' number_int = int(number_string) print(number_int) except ValueError: print('Cannot convert string to integer directly') number_float = float(number_string) number_int = int(number_float) print(number_int)
🌐
Python Principles
pythonprinciples.com › blog › python-convert-string-to-int
http://pythonprinciples.com/blog/python-convert-st...
To convert an integer to a string, use the str() built-in function. The function takes an int as input and produces a string as its output. Here are some examples. Read more → ... Understanding functions is crucial when learning to program. Different people need different explanations for ...
🌐
Reddit
reddit.com › r/learnpython › cannot use str() to convert an int to a string.
r/learnpython on Reddit: Cannot use str() to convert an int to a string.
January 18, 2022 -

Okay, so I had a crash course in Python a looooong time ago, and that's all the prior experience I have with it. I'm starting to dabble in it again, playing around with it to make a text-based game.

In this game, you have stats - Speed, Health, etc etc. Each of these is a number (an int).

I am trying to define a function names statdisplay() so that when I call on it, it prints out your stats. So, if you have a Speed of 1, and the max Speed you can increase that stat to is 5, one of the printed lines would be:

Speed: 1 / 5

This was my ORIGINAL code:

 print("\nHealth: " + healthstat + " / " + maxhealth)
 print("\nHunger: " + hungerstat + " / " + maxhunger)

 print("\nStalking Skill: " + stalkingstat + " / 5")
 print("\nHunting Skill: " + huntingstat + " / 5")

 print("\nSpeed: " + speedstat + " / 5")
 print("\nStrength: " + speedstat + " / 5")

But then I got the following error:

TypeError: can only concatenate str (not "int") to str

So I mentally facepalmed myself and looked up how to convert an int to a string, and I keep reading that you can use the str() function (I know there are other ways, but I'm taking baby steps here trying to jog my memory on how everything works before I go doing everything by what's deemed "most appropriate").

This is my NEW code with that in mind:

 print("\nHealth: " + str(healthstat) + " / " + maxhealth)
 print("\nHunger: " + str(hungerstat) + " / " + maxhunger)

 print("\nStalking Skill: " + str(stalkingstat) + " / 5")
 print("\nHunting Skill: " + str(huntingstat) + " / 5")

 print("\nSpeed: " + str(speedstat) + " / 5")
 print("\nStrength: " + str(speedstat) + " / 5")

...and yet I am still getting the following error:

TypeError: can only concatenate str (not "int") to str

I can't seem to figure out what's wrong. I do not have the str() function defined as anything else. str() also doesn't seem to come from any special libraries that I'd need to import, but maybe I'm wrong there (I tried to look it up)... the only import I currently have is "import random".

My only other thought is that maybe it's a Google Colab thing, as that's where I'm currently running my code since this wasn't anything serious and I tend to go between two different computers.

Any help would be much appreciated!

Edit: accidentally had the new code in both code boxes.