如何检查字符串是否包含字母或字母和撇号但是没有数字?

时间:2015-11-18 21:31:10

标签: python string

我试图找出是否有一个简单的方法是使用for循环和列表来检查用户输入字符串是否包含字母或字母和撇号,而不是数字,字母和数字(字母和数字)数字和撇号)?

我尝试了很多方法,似乎无法弄明白?我很感激任何线索!感谢。

2 个答案:

答案 0 :(得分:2)

您似乎只想要包含字母的字符串(加上可能是撇号),但没有数字,尽管您已经更详细地表达了要求。这可以在没有正则表达式的情况下完成,如下所示:

/* Retrieve the search term that autocomplete sends */
$term = "%{$_GET['term']}%";

/* Create a prepared statement */
$stmt = $mysql->prepare("SELECT proj AS value, projId AS id FROM projects WHERE proj LIKE ?");

/* Bind parameters ("s" for string, and bound with your term from above) */
$stmt->bind_param("s", $term);

/* Execute the query */
$stmt->execute();

/* Pass variable to hold the result */
$stmt->bind_result($value, $id);

/* Loop the results and fetch into an array */
$row_set = array();
while ($stmt->fetch()) {
    $row_set[] = array(
        'value' => $value,
        'id' => $id
    );
}

/* Close */
$stmt->close();

/* Echo the formatted array */
echo json_encode($row_set);

请参阅以下示例代码:

not any(c for c in my_str if c not in string.ascii_letters + "'")

希望显而易见的是,>>> test = ['abcde', "abcde'", 'abcde123', "abcde'123", 'abcde.'] >>> for s in test: ... print(s, '-->', not any(c for c in s if c not in string.ascii_letters + "'")) ... abcde --> True abcde' --> True abcde123 --> False abcde'123 --> False abcde. --> False 只执行一次会更高效,而且您必须先string.ascii_letters + "'"。这只是一个例子。

答案 1 :(得分:1)

您还可以使用set.issuperset指定一组允许的字符:

from string import ascii_letters
allowed = set(ascii_letters+"'")
test = ['abcde', "abcde'", 'abcde123', "abcde'123", 'abcde.']
for s in test:
   print("{} {}".format(s, allowed.issuperset(s)))

输出:

abcde True
abcde' True
abcde123 False
abcde'123 False
abcde. False
相关问题