简体   繁体   English

检查字符串是否只包含python中的某个字符

[英]Check if string only contains a certain character in python

How would I go about checking if a string only contains a certain character?我将如何检查字符串是否仅包含某个字符?

string_to_check = "aaaaaa"
character = "a"

I have tried我努力了

elif " " in cmd:
     return print(Fore.RED + f"Input cannot be nothing.")

But this applies to strings with the character in it , I would like to apply string with only the character in it ... For example但这适用于其中包含字符的字符串,我想应用仅包含字符的字符串...例如

does_contain_only("a", "aaaaaa") # True
does_contain_only("a", "aaaaba") # False

Although I don't know any commands / functions to do this,虽然我不知道任何命令/功能来做到这一点,

You could check if a string only contains a certain character, like this:您可以检查字符串是否仅包含某个字符,如下所示:

def does_contain_only(char, string):
    return all([c == char for c in string])
print(does_contain_only("a", "aaaaa")) # True
print(does_contain_only("a", "aaaba")) # False

One short solution:一个简短的解决方案:

set(string_to_check) == {'a'}

# Or, as a function:
def does_contain_only(character, target):
    return set(target) == { character }

You don't specify whether checking the empty string should return True or False.您没有指定检查空字符串是否应返回 True 或 False。 It is certainly the case that every character in an empty string is 'a' .当然,空字符串中的每个字符都是'a' Every character is also 'b' .每个字符也是'b' These are both the case because there are no characters in the empty string, so "every character is X" is trivially true for any predicate X (even if X cannot be True for any character).这两种情况都是如此,因为空字符串中没有字符,所以“每个字符都是 X”对于任何谓词 X 都是平凡的(即使 X 对于任何字符都不能是 True)。

Sometimes that's what you want and sometimes it isn't.有时这就是你想要的,有时不是。 My solution above returns False for the empty string, while the possibly more obvious all(ch == character for ch in target) would return True.我上面的解决方案为空字符串返回 False,而可能更明显的all(ch == character for ch in target)将返回 True。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM