[英]How to check if a string contains only characters from a given set in python
I have aa user-inputted polynomial and I only want to use it if it only has characters in the string 1234567890^-+x
. 我有一个用户输入的多项式,我只想使用它,如果它只有字符串
1234567890^-+x
中的字符。
How can I check if it does or not without using external packages? 如何在不使用外部包的情况下检查是否存在? I only want to use built-in Python 2.5 functions.
我只想使用内置的Python 2.5函数。
I am writing a program that runs on any Mac without needing external packages. 我正在编写一个可以在任何Mac上运行而无需外部软件包的程序。
Here are some odd ;-) ways to do it: 这里有一些奇怪的:-)方法:
good = set('1234567890^-+x')
if set(input_string) <= good:
# it's good
else:
# it's bad
or 要么
if input_string.strip('1234567890^-+x'):
# it's bad!
else:
# it's good
Use a regular expression: 使用正则表达式:
import re
if re.match('^[-0-9^+x]*$', text):
# Valid input
The re
module comes with Python 2.5, and is your fastest option. re
模块附带Python 2.5,是您最快的选择。
Demo: 演示:
>>> re.match('^[-0-9^+x]*$', '1x2^4-2')
<_sre.SRE_Match object at 0x10f0b6780>
set
, as sets offer faster lookup set
,因为集合提供更快的查找 Then you can use all
function like this 然后你可以使用这样的
all
功能
valid_chars = set("1234567890^-+x") # Converting to a set if all(char in valid_chars for char in input_string): # Do stuff if input is valid
We can convert the input string also a set and check if all characters in the inputstring is in the valid list. 我们也可以将输入字符串转换为一个集合,并检查输入字符串中的所有字符是否都在有效列表中。
valid_chars = set("1234567890^-+x") # Converting to a set if set(input_string).issubset(valid_chars): # Do stuff if input is valid
What about just convert both the string into set and checking input_set is subset of good_set
as below: 如何将字符串转换为set并检查
input_set is subset of good_set
如下所示:
>>> good_set = set('1234567890^-+x')
>>> input_set1 = set('xajfb123')
>>> input_set2 = set('122-32+x')
>>> input_set1.issubset(good_set)
False
>>> input_set2.issubset(good_set)
True
>>>
Yet another way to do it, now using string.translate()
: 还有另一种方法,现在使用
string.translate()
:
>>> import string
>>> all_chars = string.maketrans('', '')
>>> has_only = lambda s, valid_chars: not s.translate(all_chars, valid_chars)
>>> has_only("abc", "1234567890^-+x.")
False
>>> has_only("x^2", "1234567890^-+x.")
True
It is not the most readable way. 它不是最易读的方式。 It should be one of the fastest if you need it.
如果你需要它应该是最快的之一。
whitelist = '1234567890^-+x'
str = 'x^2+2x+1'
min([ch in whitelist for ch in str])
True
str='x**2 + 1'
min([ch in whitelist for ch in str])
False
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.