Python - Test if Kth character is digit in String
Last Updated :
24 Apr, 2023
Given a String, check if Kth index is a digit.
Input : test_str = 'geeks9geeks', K = 5
Output : True
Explanation : 5th idx element is 9, a digit, hence True.
Input : test_str = 'geeks9geeks', K = 4
Output : False
Explanation : 4th idx element is s, not a digit, hence False.
Method #1: Using in operator
In this, we create a string of numerics and then use in operator to check if Kth digit lies in that numeric string.
Python3
# Python3 code to demonstrate working of
# Test if Kth character is digit in String
# Using in operator
# initializing string
test_str = 'geeks4geeks'
# printing original String
print("The original string is : " + str(test_str))
# initializing K
K = 5
# checking if Kth digit is string
# getting numeric str
num_str = "0123456789"
res = test_str[K] in num_str
# printing result
print("Is Kth element String : " + str(res))
OutputThe original string is : geeks4geeks
Is Kth element String : True
Method #2 : Using isdigit()
In this, we use inbuilt Py. function to solve this problem, and check if Kth element is digit.
Python3
# Python3 code to demonstrate working of
# Test if Kth character is digit in String
# Using isdigit()
# initializing string
test_str = 'geeks4geeks'
# printing original String
print("The original string is : " + str(test_str))
# initializing K
K = 5
# isdigit checks for digit
res = test_str[K].isdigit()
# printing result
print("Is Kth element String : " + str(res))
OutputThe original string is : geeks4geeks
Is Kth element String : True
The Time and Space Complexity for all the methods are the same:
Time Complexity: O(1)
Auxiliary Space: O(1)
Method #3 : Using ord() method
Python3
# Python3 code to demonstrate working of
# Test if Kth character is digit in String
# initializing string
test_str = 'geeks4geeks'
# printing original String
print("The original string is : " + str(test_str))
# initializing K
K = 5
res=False
if(ord(test_str[K])>=48 and ord(test_str[K])<=57):
res=True
# printing result
print("Is Kth element String : " + str(res))
OutputThe original string is : geeks4geeks
Is Kth element String : True
Method #4 : Using isnumeric() method
Python3
# Python3 code to demonstrate working of
# Test if Kth character is digit in String
# Using isnumeric()
# initializing string
test_str = 'geeks4geeks'
# printing original String
print("The original string is : " + str(test_str))
# initializing K
K = 5
# isdigit checks for digit
res = test_str[K].isnumeric()
# printing result
print("Is Kth element String : " + str(res))
OutputThe original string is : geeks4geeks
Is Kth element String : True
Time Complexity : O(1)
Auxiliary Space : O(1)
Method #5 : Using try-except block
Algorithm:
- Initialize the test_str variable with a given string.
- Print the original string.
- Initialize the K variable with a given value.
- Use try-except block to check if Kth element is a digit.
- If the Kth element is a digit, then set res to True, else False.
- Print the result.
Python3
# initializing string
test_str = 'geeks4geeks'
# printing original String
print("The original string is : " + str(test_str))
# initializing K
K = 5
# using try-except
try:
# checking if Kth element is digit
int(test_str[K])
res = True
except ValueError:
res = False
# printing result
print("Is Kth element String : " + str(res))
#this code is contributed Asif_Shaik
OutputThe original string is : geeks4geeks
Is Kth element String : True
Time complexity: O(1)
The time complexity of this code is O(1) because it only performs a constant number of operations regardless of the length of the input string.
Auxiliary space: O(1)
The auxiliary space complexity of this code is O(1) because it only uses a constant amount of extra space to store the Boolean result.
Method 6 : using regular expressions.
step-by-step approach
- Import the re module to use regular expressions.
- Define a regular expression pattern that matches a single digit. In regular expressions, the \d character class represents a digit. So, our pattern will be r"\d".
- Use the re.match() function to check if the Kth character matches the pattern. We can access the Kth character using string indexing, like test_str[K]. If the character matches the pattern, the match() function returns a match object, which is a truthy value in Python. If the character does not match the pattern, the function returns None, which is a falsy value in Python.
- Based on the return value of the match() function, set the value of the res variable to True or False.
- Print the result.
Python3
import re
# initializing string
test_str = 'geeks4geeks'
# printing original string
print("The original string is : " + str(test_str))
# initializing K
K = 5
# regular expression pattern for a single digit
pattern = r"\d"
# check if the Kth character matches the pattern
match = re.match(pattern, test_str[K])
# set the value of res based on the match result
res = bool(match)
# printing result
print("Is Kth element String : " + str(res))
OutputThe original string is : geeks4geeks
Is Kth element String : True
Time complexity: The time complexity of this method is O(1), as it only involves matching a single character with a regular expression pattern, which takes constant time.
Auxiliary space: The auxiliary space used by this method is also O(1), as it only involves storing a regular expression pattern and a match object, both of which take constant space.
Similar Reads
Python - Test String in Character List and vice-versa
Given a String, check if it's present in order in the character list and vice versa. Input : test_str = 'geeks', K = ['g', 'e', 'e', 'k', 'f', 'o', 'r', 'g', 'e', 'e', 'k', 's'] [ String in Character list ] Output : True Explanation : geeks is present in list , starting from 7th index till end. Inpu
3 min read
Python - First K consecutive digits in String
Given a String and number K, extract first K consecutive digits making number. Input : test_str = "geeks5geeks43best", K = 2 Output : 43 Explanation : 43 is first 2 consecutive digits. Input : test_str = "geeks5gee2ks439best", K = 3 Output : 439 Explanation : 439 is first 3 consecutive digits. Metho
5 min read
Python - Lowercase Kth Character in string
The problem of lowercasing a string is quite common and has been discussed many times. But sometimes, we might have a problem like this in which we need to convert the Nth character of string to lowercase. Letâs discuss certain ways in which this can be performed. Method #1 : Using string slicing +
4 min read
Python - Test if String contains any Uppercase character
The goal is to check if a given string contains at least one uppercase letter (A-Z). Using any() and isupper()any() function, combined with isdigit(), checks if any character in a string is a digit. It efficiently scans the string and returns True if at least one digit is found.Python# Define the in
3 min read
Python | Checking if starting digits are similar in list
Sometimes we may face a problem in which we need to find a list if it contains numbers with the same digits. This particular utility has an application in day-day programming. Let's discuss certain ways in which this task can be achieved. Method #1: Using list comprehension + map() We can approach t
8 min read
Find position of a character in given string - Python
Given a string and a character, our task is to find the first position of the occurrence of the character in the string using Python. For example, consider a string s = "Geeks" and character k = 'e', in the string s, the first occurrence of the character 'e' is at index1. Let's look at various metho
2 min read
Check if string contains character - Python
We are given a string and our task is to check if it contains a specific character, this can happen when validating input or searching for a pattern. For example, if we check whether 'e' is in the string 'hello', the output will be True.Using in Operatorin operator is the easiest way to check if a c
2 min read
Python - Test if all digits starts from % K digit
Sometimes we may face a problem in which we need to find for a list if it contains numbers which are % K. This particular utility has an application in day-day programming. Letâs discuss certain ways in which this task can be achieved. Method #1 : Using list comprehension + map() We can approach thi
5 min read
Python - Test rear digit match in all list elements
Sometimes we may face a problem in which we need to find a list if it contains numbers ending with the same digits. This particular utility has an application in day-day programming. Letâs discuss certain ways in which this task can be achieved. Method #1: Using list comprehension + map() We can app
6 min read
Python | Check if string is a valid identifier
Given a string, write a Python program to check if it is a valid identifier or not. An identifier must begin with either an alphabet or underscore, it can not begin with a digit or any other special character, moreover, digits can come after gfg : valid identifier 123 : invalid identifier _abc12 : v
3 min read