Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Check if String Has the same characters in Python [duplicate]

Tags:

python

What is the shortest way to check if a given string has the same characters?

For example if you have name = 'aaaaa' or surname = 'bbbb' or underscores = '___' or p = '++++', how do you check to know the characters are the same?

like image 710
Yax Avatar asked Sep 22 '16 08:09

Yax


People also ask

How do you know if a string has repeated letters?

If we want to know whether a given string has repeated characters, the simplest way is to use the existing method of finding first occurrence from the end of the string, e.g. lastIndexOf in java. In Python, the equivalence would be rfind method of string type that will look for the last occurrence of the substring.


3 Answers

An option is to check whether the set of its characters has length 1:

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

Or with all(), this could be faster if the strings are very long and it's rare that they are all the same character (but then the regex is good too):

>>> s = "aaaaa"
>>> s0 = s[0]
>>> all(c == s0 for c in s[1:])
True
like image 185
RemcoGerlich Avatar answered Oct 06 '22 01:10

RemcoGerlich


You can use regex for this:

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

Here's an explanation of what this regex pattern means: https://regexper.com/#%5E(.)%5C1*%24

like image 38
Cristian Lupascu Avatar answered Oct 06 '22 00:10

Cristian Lupascu


Also possible:

s = "aaaaa"
s.count(s[0]) == len(s)
like image 32
nauer Avatar answered Oct 05 '22 23:10

nauer