How to convert string to integer in Python? Last Updated : 10 Jul, 2020 Comments Improve Suggest changes Like Article Like Report In Python, a string can be converted into an integer using the following methods : Method 1: Using built-in int() function: If your string contains a decimal integer and you wish to convert it into an int, in that case, pass your string to int() function and it will convert your string into an equivalent decimal integer. Syntax : int(string, base) Parameter : This function take following parameters : string : consists of 1's, 0's or hexadecimal ,octal digits etc. base : (integer value) base of the number. Returns : Returns an integer value, which is equivalent of string in the given base. Code : Python3 # Initialising a string # with decimal value string = "100" # Show the Data type print(type(string)) # Converting string into int string_to_int = int(string) # Show the Data type print(type(string_to_int)) Output: <class 'str'> <class 'int'> By default, int() expect that the string argument represents a decimal integer. Assuming, in any case, you pass a hexadecimal string to int(), then it will show ValueError. In such cases, you can specify the base of the number in the string. Code: Python3 # Initialising a string # with hexadecimal value string = "0x12F" # Show the Data type print(type(string)) # Converting hexadecimal # string into int string_to_int = int(string, base=16) # Show the Data type print(type(string_to_int)) Output: <class 'str'> <class 'int'> Method 2: Using user-defined function: We can also convert a string into an int by creating our own user-defined function. Approach: we'll check, if the number has any “-” sign or not, for if it is a negative number it will contain “-” sign. If it contains “-” sign, then we will start our conversion from the second position which contains numbers.Any number, suppose 321, can be written in the structure : 10**2 * 3 + 10**1*2 + 10**0*1Similarly, we split each of the input number using ord(argument), ord('0') will return 48, ord('1') returns 49 and so forth.The logic here is that ord('1') – ord('0) = 1, ord('2') – ord('0') = 2 and so on which gives us the significant number to be fetched from the given input number.Finally, the result we get from the function is an Integral number which we changed over from the given string. Code: Python3 # User-defined function to # convert a string into integer def string_to_int(input_string): output_int = 0 # Check if the number contains # any minus sign or not, # i.e. is it a negative number or not. # If it contains in the first # position in a minus sign, # we start our conversion # from the second position which # contains numbers. if input_string[0] == '-' : starting_idx = 1 check_negative = True else: starting_idx = 0 check_negative = False for i in range(starting_idx, len(input_string)): # calculate the place value for # the respective digit place_value = 10**(len(input_string) - (i+1)) # calculate digit value # ord() function gives Ascii value digit_value = ord(input_string[i]) - ord('0') # calculating the final integer value output_int += place_value * digit_value # if check_negative is true # then final integer value # is multiplied by -1 if check_negative : return -1 * output_int else: return output_int # Driver code if __name__ == "__main__" : string = "554" # function call x = string_to_int(string) # Show the Data type print(type(x)) string = "123" # Show the Data type print(type(string_to_int(string))) string = "-123" # Show the Data type print(type(string_to_int(string))) Output: <class 'int'> <class 'int'> <class 'int'> Comment More infoAdvertise with us Next Article Iterate over characters of a string in Python ankthon Follow Improve Article Tags : Python python-string python-basics Practice Tags : python Similar Reads Python String A string is a sequence of characters. Python treats anything inside quotes as a string. This includes letters, numbers, and symbols. Python has no character data type so single character is a string of length 1.Pythons = "GfG" print(s[1]) # access 2nd char s1 = s + s[0] # update print(s1) # printOut 6 min read Why are Python Strings Immutable? Strings in Python are "immutable" which means they can not be changed after they are created. Some other immutable data types are integers, float, boolean, etc. The immutability of Python string is very useful as it helps in hashing, performance optimization, safety, ease of use, etc. The article wi 5 min read Python - Modify Strings Python provides an wide range of built-in methods that make string manipulation simple and efficient. In this article, we'll explore several techniques for modifying strings in Python.Start with doing a simple string modification by changing the its case:Changing CaseOne of the simplest ways to modi 3 min read Python String ManipulationsPython string lengthThe string len() function returns the length of the string. In this article, we will see how to find the length of a string using the string len() method.Example:Pythons1 = "abcd" print(len(s1)) s2 = "" print(len(s2)) s3 = "a" print(len(s3))Output4 0 1 String len() Syntaxlen(string) ParameterString: 4 min read String Slicing in PythonString slicing in Python is a way to get specific parts of a string by using start, end and step values. Itâs especially useful for text manipulation and data parsing.Letâs take a quick example of string slicing:Pythons = "Hello, Python!" print(s[0:5])OutputHello Explanation: In this example, we use 4 min read How to reverse a String in PythonReversing a string is a common task in Python, which can be done by several methods. In this article, we discuss different approaches to reversing a string. One of the simplest and most efficient ways is by using slicing. Letâs see how it works:Using string slicingThis slicing method is one of the s 4 min read Find Length of String in Python In this article, we will learn how to find length of a string. Using the built-in function len() is the most efficient method. It returns the number of items in a container. Pythona = "geeks" print(len(a)) Output5 Using for loop and 'in' operatorA string can be iterated over, directly in a for loop. 2 min read How to convert string to integer in Python?In Python, a string can be converted into an integer using the following methods : Method 1: Using built-in int() function: If your string contains a decimal integer and you wish to convert it into an int, in that case, pass your string to int() function and it will convert your string into an equiv 3 min read Iterate over characters of a string in Python In this article, we will learn how to iterate over the characters of a string in Python. There are several methods to do this, but we will focus on the most efficient one. The simplest way is to use a loop. Letâs explore this approach.Using for loopThe simplest way to iterate over the characters in 2 min read Python String Concatenation and ComparisonString Comparison in PythonPython supports several operators for string comparison, including ==, !=, <, <=, >, and >=. These operators allow for both equality and lexicographical (alphabetical order) comparisons, which is useful when sorting or arranging strings.Letâs start with a simple example to illustrate the 3 min read Python String ConcatenationString concatenation in Python allows us to combine two or more strings into one. In this article, we will explore various methods for achieving this. The most simple way to concatenate strings in Python is by using the + operator.Using + OperatorUsing + operator allows us to concatenation or join s 3 min read Python - Horizontal Concatenation of Multiline StringsHorizontal concatenation of multiline strings involves merging corresponding lines from multiple strings side by side using methods like splitlines() and zip(). Tools like itertools.zip_longest() help handle unequal lengths by filling missing values, and list comprehensions format the result.Using z 3 min read String Repetition and spacing in List - PythonWe are given a list of strings and our task is to modify it by repeating or adding spaces between elements based on specific conditions. For example, given the list `a = ['hello', 'world', 'python']`, if we repeat each string twice, the output will be `['hellohello', 'worldworld', 'pythonpython']. U 2 min read Python String FormattingPython String Formatting - How to format String?String formatting allows you to create dynamic strings by combining variables and values. In this article, we will discuss about 5 ways to format a string.You will learn different methods of string formatting with examples for better understanding. Let's look at them now!How to Format Strings in Pyt 9 min read What does %s mean in a Python format string?In Python, the %s format specifier is used to represent a placeholder for a string in a string formatting operation. It allows us to insert values dynamically into a string, making our code more flexible and readable. This placeholder is part of Python's older string formatting method, using the % o 3 min read Python String InterpolationString Interpolation is the process of substituting values of variables into placeholders in a string. Let's consider an example to understand it better, suppose you want to change the value of the string every time you print the string like you want to print "hello <name> welcome to geeks for 4 min read Python Modulo String FormattingIn Python, a string of required formatting can be achieved by different methods. Some of them are; 1) Using % 2) Using {} 3) Using Template Strings In this article the formatting using % is discussed. The formatting using % is similar to that of 'printf' in C programming language. %d - integer %f - 2 min read How to use String Formatters in PythonIn Python, we use string formatting to control how text is displayed. It allows us to insert values into strings and organize the output in a clear and readable way. In this article, weâll explore different methods of formatting strings in Python to make our code more structured and user-friendly.Us 3 min read Python String format() Methodformat() method in Python is a tool used to create formatted strings. By embedding variables or values into placeholders within a template string, we can construct dynamic, well-organized output. It replaces the outdated % formatting method, making string interpolation more readable and efficient. E 8 min read f-strings in PythonPython offers a powerful feature called f-strings (formatted string literals) to simplify string formatting and interpolation. f-strings is introduced in Python 3.6 it provides a concise and intuitive way to embed expressions and variables directly into strings. The idea behind f-strings is to make 5 min read Python String Methods Python string methods is a collection of in-built Python functions that operates on strings.Note: Every string method in Python does not change the original string instead returns a new string with the changed attributes. Python string is a sequence of Unicode characters that is enclosed in quotatio 5 min read Python String Exercise Basic String ProgramsCheck whether the string is Symmetrical or PalindromeFind length of StringReverse words in a given StringRemove iâth character from stringAvoid Spaces in string lengthPrint even length words in a stringUppercase Half StringCapitalize the first and last character of each word in 4 min read Like