9
a = '4-6'
b= '7:10'

I have already tried

a.split('-')
a.split(':')

how can i write code that can take in either string and get rid of both colons and hyphens? Is there a better way besides splitting the same string twice?

dustinyourface
  • 313
  • 1
  • 3
  • 9
  • Are you trying to make a list of all elements seperated by either a '-' or ':'. Or just remove those characters from the string and return the new string sans thats character? – Malonge Apr 16 '15 at 22:53
  • Duplicate of many different questions. The one marked and [Python: Split string with multiple delimiters](http://stackoverflow.com/questions/4998629/python-split-string-with-multiple-delimiters) – dawg Apr 17 '15 at 00:11

2 Answers2

17

To split on more than one delimiter, you can use re.split and a character set:

import re
re.split('[-:]', a)

Demo:

>>> import re
>>> a = '4-6'
>>> b = '7:10'
>>> re.split('[-:]', a)
['4', '6']
>>> re.split('[-:]', b)
['7', '10']

Note however that - is also used to specify a range of characters in a character set. For example, [A-Z] will match all uppercase letters. To avoid this behavior, you can put the - at the start of the set as I did above. For more information on Regex syntax, see Regular Expression Syntax in the docs.

  • You should mention that this is called a regular expression. – wvdz Apr 16 '15 at 22:50
  • 1
    I think regular expressions should be avoided in the case of beginners. – Malik Brahimi Apr 16 '15 at 22:51
  • 2
    @MalikBrahimi - Why? In my opinion, they are a very useful tool that every programmer should be aware of. Now that's not to say they should be used *everywhere*, but in this case, a Regex solution is nice and simple. –  Apr 16 '15 at 22:59
4

You can replace one by the other then split the entire string:

parts = your_string.replace('-', ':').split(':')
Malik Brahimi
  • 16,341
  • 7
  • 39
  • 70