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?
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?
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 can replace one by the other then split the entire string:
parts = your_string.replace('-', ':').split(':')