efficiently checking that string consists of one character in Python

后端 未结 8 1366
太阳男子
太阳男子 2020-11-29 01:03

What is an efficient way to check that a string s in Python consists of just one character, say \'A\'? Something like all_equal(s, \'A\')

8条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-11-29 02:00

    Interesting answers so far. Here's another:

    flag = True
    for c in 'AAAAAAAfAAAA':
        if not c == 'A': 
            flag = False
            break
    

    The only advantage I can think of to mine is that it doesn't need to traverse the entire string if it finds an inconsistent character.

提交回复
热议问题