我想确定是否只使用列表中的字符创建字符串。例如,
>>>acceptableChars = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i']
>>>print isAcceptable("abc")
True
>>>print isAcceptable("xyz")
False
答案 0 :(得分:4)
从acceptableChars
制作一套:
>>> acceptableChars = set('abcdefghi')
现在我们可以使用set减法检查isAcceptable,检查其参数中的任何字符是否不在acceptableChars
中:
>>> def isAcceptable(s):
return set(s) <= acceptableChars
>>> isAcceptable("abc")
True
>>> isAcceptable("xyz")
False
答案 1 :(得分:3)
因为您的实际用例是:
我正在使用它来检查某些东西是否为哈希值(0-9,a-f),因此任何数量的重复都是可以接受的
这个怎么样:
intvalue = int(possiblehash, 16)
如果成功,这意味着它是一个有效的十六进制字符串 - 并且您有值,以备需要时使用。如果它引发异常,则它不是有效的十六进制字符串。所以:
try:
intvalue = int(possiblehash, 16)
except Exception as e:
print("That's not a hex string! Python says " + str(e))
如果您想使用不同的方法将十六进制字符串转换为某种适当的形式而不是整数,则完全相同的想法将适用:
try:
binvalue = binascii.unhexlify(possiblehash)
except Exception as e:
print("That's not a hex string! Python says " + str(e))
答案 2 :(得分:2)
def isAcceptable(text, acceptableChars=set("abcdefghi")):
return all(char in acceptableChars for char in text)
答案 3 :(得分:0)
一种可能性就是循环遍历字符串:
def isAcceptable(s):
for c in s:
if not isAcceptableChar(c):
return False
return True
如何编写isAcceptableChar
函数应该非常明显。
当然,如果您对Python有更多了解,那么您可能只想写:
def isAcceptable(s):
return all(isAcceptableChar(c) for c in s)
如果你对集合理论有所了解,你可能会提出一种更有效,更简单的实现。
但首先让基本的工作正常,然后考虑如何改进它。
答案 4 :(得分:0)
In [52]: all(c in acceptableChars and acceptableChars.count(c)==want.count(c) for c in want)
Out[52]: True
In [53]: acceptableChars = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i']
In [54]: want = 'abc'
In [55]: all(c in acceptableChars and acceptableChars.count(c)==want.count(c) for c in want)
Out[55]: True
In [56]: want = 'xyz'
In [57]: all(c in acceptableChars and acceptableChars.count(c)==want.count(c) for c in want)
Out[57]: False
尽管如此,以下是更好的方法:
def isAcceptable(text, chars):
store = collections.Counter(chars)
for char in text:
if char not in store or not store[char]:
return False
store[char] -= 1
return True
答案 5 :(得分:0)
我能想到的最简单的方法:检查yourString.strip('all your acceptable chars')
是否为您返回一个空白字符串。
def isAcceptable(text, acceptable='abcdefghi'):
return text.strip(acceptable) == ''
如果strip
返回''
,则text
中的唯一字符也位于acceptable
。