Movatterモバイル変換


[0]ホーム

URL:


Open In App

Convert String to Int means changing a value written as text (string) into a number (integer) so you can do math with it.

Using int() Function

The simplest way to convert a string to an integer in Python is by using the int() function. This function attempts to parse the entire string as a base-10 integer.

Python
s="42"num=int(s)print(num)

Output
42

Explanation: The int() function takes the strings and converts it into an integer.

Note:

  • If the string contains non-numeric characters or is empty, int() will raise a ValueError.
  • int() function automatically handles leading and trailing whitespaces, so int() function trims whitespaces and converts the core numeric part to an integer.

Converting Strings with Different Bases

Theint() function also supports other number bases, such as binary (base-2) or hexadecimal (base-16). To specify the base during conversion, we have to provide the base in the second argument of int().

Python
# Binary strings="1010"num=int(s,2)print(num)# Hexadecimal strings="A"num=int(s,16)print(num)

Output
1010

Explanation:

  • Here, int(s, 2) interpretssas a binary string, returning10 in decimal.
  • Similarly,int(s, 16) treatss as a hexadecimal string.

Handling Invalid Input String

Using try and except

If the input string contains non-numeric characters,int()will raise aValueError. To handle this gracefully, we use atry-exceptblock.

Python
s="abc"try:num=int(s)print(num)exceptValueError:print("Invalid input: cannot convert to integer")

Output
Invalid input: cannot convert to integer

Explanation:

  • try attempts to convert the strings to an integer.
  • Ifs contains non-numeric characters, aValueError is raised and we print an error message instead.

Using str.isdigit()

Usestr.isdigit()to check if a string is entirely numeric before converting. This method make sure that the input only contains digits.

Python
s="12345"ifs.isdigit():num=int(s)print(num)else:print("The string is not numeric.")

Output
12345

Explanation: s.isdigit()returnsTrue ifscontains only digits, this allow us safe conversion to an integer.


Python Program to Convert String to an Integer
Improve

Explore

Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences

[8]ページ先頭

©2009-2025 Movatter.jp