如何检查字符串是否在Python中具有相同的字符

时间:2016-09-22 08:51:57

标签: python

检查给定字符串是否具有相同字符的最短方法是什么?

例如,如果您有name = 'aaaaa'surname = 'bbbb'underscores = '___'p = '++++',您如何检查字符是否相同?

6 个答案:

答案 0 :(得分:16)

一个选项是检查其字符集是否长度为1:

>>> len(set("aaaa")) == 1
True

或者使用all(),如果字符串非常长并且它们都是相同的字符很少见(但正则表达式也很好),这可能会更快:

>>> s = "aaaaa"
>>> s0 = s[0]
>>> all(c == s0 for c in s[1:])
True

答案 1 :(得分:3)

您可以使用正则表达式:

import re
p = re.compile(ur'^(.)\1*$')     

re.search(p, "aaaa") # returns a match object
re.search(p, "bbbb") # returns a match object
re.search(p, "aaab") # returns None

以下是对此正则表达式模式的含义的解释:https://regexper.com/#%5E(.)%5C1 *%24

答案 2 :(得分:2)

也可能:

s = "aaaaa"
s.count(s[0]) == len(s)

答案 3 :(得分:1)

compare == len(name) * name[0]

if(compare):
    # all characters are same
else:
    # all characters aren't same

答案 4 :(得分:1)

以下是两种方式。

def all_match0(s):
    head, tail = s[0], s[1:]
    return tail == head * len(tail)

def all_match1(s):
    head, tail = s[0], s[1:]
    return all(c == head for c in tail)

all_match = all_match0

data = [
    'aaaaa',
    'bbbb',
    '___',
    '++++',
    'q',
    'aaaaaz',
    'bbbBb',
    '_---',
]

for s in data:
    print(s, all_match(s))

<强>输出

aaaaa True
bbbb True
___ True
++++ True
q True
aaaaaz False
bbbBb False
_--- False
除非字符串很长,否则

all_match0会更快,因为它的测试循环以C速度运行,但它使用更多的RAM,因为它构造了一个重​​复的字符串。对于非常长的字符串,构造重复字符串所花费的时间变得非常重要,当然,在创建重复字符串之前,它不能进行任何测试。

all_match1应该稍微慢一点,即使对于短字符串也是如此,并且因为一旦发现不匹配就会停止测试,如果不匹配发生在all_match0,它可能会比import template from './tech.html' import styles from './styles.mcss' import TechService from './techService'; class Controller { constructor(TechService) { // css modules TechService.consoleLog(); this.styles = styles; } } export const tech = { template, bindings: { tech: '<' }, controller: Controller }; 快。字符串。

答案 5 :(得分:1)

尝试使用Counter(高性能容器数据类型)。

>>> from collections import Counter
>>> s = 'aaaaaaaaa'
>>> c = Counter(s)
>>> len(c) == 1
True