Python – 测试第 K 个字符是否是字符串中的数字
给定一个字符串,检查第 K 个索引是否为数字。
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.
方法 #1:使用 in运算符
在此,我们创建一个数字字符串,然后使用 in运算符检查第 K 个数字是否位于该数字字符串中。
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))
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))
输出
The original string is : geeks4geeks
Is Kth element String : True
方法#2:使用 isdigit()
在此,我们使用内置的 Py。函数来解决这个问题,并检查第 K 个元素是否为数字。
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))
输出
The original string is : geeks4geeks
Is Kth element String : True