How can I check if a string consists only of (multiple) dashes? '-', '--', '---', and so on need to be True, but e.g. '-3', 'foo--', and the like need to be False. What is the best way to check for that?
Asked
Active
Viewed 1,750 times
-5
frixhax
- 1,325
- 3
- 18
- 30
-
2Count them and compare it to the length? – Ashwini Chaudhary Jan 06 '15 at 09:06
-
It's the same as the duplicate, just change the checks where it does `my_list[0]` to whatever character you want eg `'-'`. As you can see all the answers here are the same as the dupe thread – jamylak Jan 06 '15 at 10:01
-
Thanks. However the code from the link returns for this list `['---', '-', '--', 'asd-', '--asd', '']` `True, True, True, False, False, True` instead of the desired `True, True, True, False, False, False` and I'm not quite sure why - obviously because if the empty string, but how can I fix that? – frixhax Jan 06 '15 at 11:09
5 Answers
3
There are many ways, but I think the most straighforward one is:
all(i == '-' for i in '----')
utdemir
- 26,532
- 10
- 62
- 81
3
You can use the builtin function all:
>>> a= '---'
>>> all(i == '-' for i in a)
True
>>> b="----c"
>>> all(i == '-' for i in b)
False
fredtantini
- 15,966
- 8
- 49
- 55
3
The most obvious ways are:
- Is the string equal to the string it would be if it were all dashes:
s == '-' * len(s); - Does the string contain as many dashes as its length:
s.count('-') == len(s); - Is the
setof the string just a dash:set(s) == set('-'); - Does the string match a regular expression for only dashes:
re.match(r'^-+$', s); and - Are
allthe characters in the string dashes:all(c == '-' for c in s).
There are no doubt other options; in terms of "best", you would have to define your criteria. Also, what should an empty string "" result in? All of the no characters in it are dashes...
jonrsharpe
- 115,751
- 26
- 228
- 437
2
One way would be to use a set.
>>> a = '---'
>>> len(set(a)) == 1 and a[0] == '-'
True
>>> a = '-x-'
>>> len(set(a)) == 1 and a[0] == '-'
False
If the length of the set is 1 there is only one distinct character in the string. Now we just have to check if this character is a '-'.
An easier way would be to compare sets.
>>> set('----') == set('-')
True
>>> set('--x') == set('-')
False
Matthias
- 12,873
- 6
- 42
- 48
-
The latter seems rather elegant and works even for empty strings, unlike the example given in the 'duplicate', which hence is not really one. – frixhax Jan 06 '15 at 12:12
1
>>> import re
>>> def check(str):
... if re.match(r"-+$", str):
... return True
... return False
...
>>> check ("--")
True
>>> check ("foo--")
False
OR
Shorter
>>> def check(str):
... return bool ( re.match(r"-+$", str))
nu11p01n73R
- 26,397
- 3
- 39
- 52
-
You're missing an anchor for the end of the string. `check('-x')` will return `True` with your code. Use `r"-+$"` instead. – Matthias Jan 06 '15 at 09:14
-
you could use `return bool(re.match("-*$", s))` (return True for an empty string like other solutions) – jfs Jan 06 '15 at 09:22
-