PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Wednesday, July 20, 2022

[FIXED] How to check if a number has subscript in it in Python?

 July 20, 2022     integer, python, python-3.x     No comments   

Issue

I have a string which is like: t = '²'

This throws my code off: int(t) with the error:

ValueError: invalid literal for int() with base 10: '²'

How do I detect if a string is a superscript and not a real integer?

I just want to cast a string number to int and get the integer. I want to make sure that the numbers I pass doesn't throw the above error.

I don't want to use try/except block.


Solution

The is_digit method returns True for subscripts and superscripts. You can use a combination of int and is_digit to implement that:

def is_subscript(s):
    if s.isdigit():
        try:
            int(s)
        except ValueError:
            return True
    return False

Then

print(is_subscript('²'))   # Should print True
print(is_subscript('2'))   # Should print False


Answered By - Selcuk
Answer Checked By - Willingham (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing