Python – 检查元素是否由 K 分隔
给定一个字符串,检查每个段是否由 K 分隔。
Input : test_str = ’72!45!geeks!best’, K = ‘!’
Output : True
Explanation : All numerics and alphabets separated by delim border.
Input : test_str = ’72!45geeks!best’, K = ‘!’
Output : False
Explanation : No separation between 45 and geeks.
方法:使用 isdigit() + isalpha() + 循环
这是可以执行此任务的方式。在此,我们使用 isalpha() 和 isdigit() 执行检查字母和数字段的任务。任何元素的存在,不完全是数字或字母,都被称为不被 K 分隔,并且在 split() 期间仍未解决。
Python3
# Python3 code to demonstrate working of
# Check if Elements delimited by K
# Using isdigit() + isalpha() + loop
# initializing string
test_str = '72@45@geeks@best'
# printing original string
print("The original string is : " + str(test_str))
# initializing splt_chr
K = "@"
res = True
# splitting elements
temp = test_str.split(K)
for ele in temp:
# checking for non-alpha or non-digit
if len(ele) > 1 and not ele.isdigit() and not ele.isalpha():
res = False
break
# printing result
print("Are all delimited by K : " + str(res))
输出
The original string is : 72@45@geeks@best
Are all delimited by K : True