[英]Simple way to accept only one form of delimiter and rejecting multiple types?
I was wondering how I could go about making something that accepts a string with only one type of delimiter, something like this: 我想知道如何制作只接受一种分隔符的字符串,如下所示:
car:bus:boat
and rejecting something like: 并拒绝类似:
car:bus-boat
I am not really sure about how to go about creating something like this. 我不确定如何创建这样的东西。
Well, first you have to define what are invalid limiters. 好吧,首先您必须定义什么是无效的限制器。 A hyphen could well be part of a valid hyphenated word or name, and the algorithm wouldn't be able to tell those apart.
连字符很可能是有效的带连字符的单词或名称的一部分,并且该算法无法将它们区分开。 Supposing you have a list of invalid delimiters, you could just do:
假设您有一个无效的定界符列表,则可以执行以下操作:
def string_is_valid(s):
invalid_delimiters = ['-', ';']
for d in invalid_delimiters:
if d in s:
return False
return True
s1 = 'car:bus-boat'
print(string_is_valid(s1)) # False
s2 = 'car:bus:boat'
print(string_is_valid(s2)) # True
If, on the other hand, you have a list of delimiters and you want to make sure that only one type is present on the string, you could do this: 另一方面,如果您有一个定界符列表,并且想要确保字符串中仅存在一种类型,则可以执行以下操作:
def string_is_valid(s):
valid_delimiters = [',', ':', ';']
# For each delimiter in our list...
for d in valid_delimiters:
# If the delimiter is present in the string...
if d in s:
# If any of the other delimiters is in s (and the other delimiter isn't the same one we're currently looking at), return False (it's invalid)
if any([other_d in s and other_d != d for other_d in valid_delimiters]):
return False
return True
s1 = 'car:bus:boat'
print(string_is_valid(s1)) # True
s2 = 'car,bus,boat'
print(string_is_valid(s2)) # True
s3 = 'car,bus;boat'
print(string_is_valid(s3)) # False
you can have an alphabet of "allowed" characters and count whatever is not on it (hence interpreting it as a sep). 您可以使用字母“允许”的字符,并计算不包含在其中的任何字符(因此将其解释为sep)。
eg 例如
allowed = list('abcdefghijklmnopqrstuvxwyz')
def validate(string):
if len(set([k for k in string if k not in allowed])) > 1:
return False
return True
Of course you can expand the allowed for capital letters etc. 当然,您可以扩展允许的大写字母等。
Use regex expression: 使用正则表达式:
import re
data = re.compile(r'^([a-zA-Z][:][a-zA-Z]){1, }$')
data.match(string)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.