0

我想确定是否可以仅使用列表中的字符创建字符串。例如,

>>>acceptableChars = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i']
>>>print isAcceptable("abc")
True
>>>print isAcceptable("xyz")
False
4

6 回答 6

4

制作一组acceptableChars

>>> acceptableChars = set('abcdefghi')

现在我们可以让 isAcceptable 检查其参数中的任何字符是否不acceptableChars使用集合减法:

>>> def isAcceptable(s):
    return set(s) <= acceptableChars
>>> isAcceptable("abc")
True
>>> isAcceptable("xyz")
False
于 2012-12-12T21:49:57.977 回答
3

Since your actual use case is:

I'm using this to check if something is a hash (0-9, a-f), so any number of duplicates would be acceptable

How about this:

intvalue = int(possiblehash, 16)

If this succeeds, that means it was a valid hex string—and you have the value, in case you need it. If it raises an exception, it wasn't a valid hex string. So:

try:
   intvalue = int(possiblehash, 16)
except Exception as e:
   print("That's not a hex string! Python says " + str(e))

If you want to use a different means to convert the hex string into some appropriate form instead of an integer, the exact same idea will apply:

try:
    binvalue = binascii.unhexlify(possiblehash)
except Exception as e:
   print("That's not a hex string! Python says " + str(e))
于 2012-12-12T22:07:10.677 回答
2
def isAcceptable(text, acceptableChars=set("abcdefghi")):
    return all(char in acceptableChars for char in text)
于 2012-12-12T21:49:59.370 回答
0

我能想到的最简单的方法:检查是否yourString.strip('all your acceptable chars')返回一个空白字符串。

def isAcceptable(text, acceptable='abcdefghi'):
    return text.strip(acceptable) == ''

如果stripreturn '',那么其中唯一的字符也在text其中acceptable

于 2012-12-12T21:52:26.683 回答
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)

如果你对集合论有所了解,你可能会想出一个更高效、更简单的实现。

但首先要让基本的工作正常,然后考虑如何改进它。

于 2012-12-12T21:50:07.973 回答
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
于 2012-12-12T21:50:21.497 回答