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?
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.
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
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
Also possible:
s = "aaaaa"
s.count(s[0]) == len(s)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With