-5

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?

frixhax
  • 1,175
  • 2
  • 16
  • 30
  • 2
    Count 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 Answers5

3

There are many ways, but I think the most straighforward one is:

all(i == '-' for i in '----')
utdemir
  • 25,564
  • 10
  • 59
  • 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
  • 14,608
  • 7
  • 46
  • 54
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 set of the string just a dash: set(s) == set('-');
  • Does the string match a regular expression for only dashes: re.match(r'^-+$', s); and
  • Are all the 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
  • 107,083
  • 22
  • 201
  • 376
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
  • 11,699
  • 5
  • 39
  • 45
  • 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

Using re.match function

>>> 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
  • 25,677
  • 2
  • 36
  • 50