2

I was wondering how to correctly split the string when you have an unknown number of underscores. My input looks like this:

One Two_________1.0 2.0 3.0
Three Four______4.0 5.0 6.0
Five Six________7.0 8.0 9.0

Between words and numbers there is unknown number of underscores. I need to split this input into words and numbers. I tried using split in this way:

details = input.split("_")
words = details[0]
numbers = details[1]

However, it correctly saves only words. It worked when I changed the input to have only one underscore, however I just cannot find the solution when it has multiple underscores.

Bhargav Rao
  • 50,140
  • 28
  • 121
  • 140
A. Black
  • 43
  • 4
  • 1
    Possible duplicate of [Python split consecutive delimiters](https://stackoverflow.com/questions/6478845/python-split-consecutive-delimiters) or [How can I split by 1 or more occurrences of a delimiter in Python?](https://stackoverflow.com/questions/2492415/how-can-i-split-by-1-or-more-occurrences-of-a-delimiter-in-python) – pault Jan 23 '19 at 22:46

3 Answers3

5

You can use regexes for this.

import re
re.split('_+', 'asd___fad')
>>> ['asd', 'fad']

Basically, this is saying "split when you see one underscore (the underscore in split's first arg) or more (the plus following that underscore)"

a p
  • 3,098
  • 2
  • 24
  • 46
  • 1
    Thank you, this solved the problem completely! This solution was easy to implement in my program and was clear to use. – A. Black Jan 23 '19 at 22:55
0

use negative indexing. I.E. numbers = details[-1]

Reedinationer
  • 5,661
  • 1
  • 12
  • 33
  • you can use regular expressions (regexes) as well, but these can be complicated to implement if you don't understand what you're doing – Reedinationer Jan 23 '19 at 22:25
0

Using just builtins:

# slices input from beginning to first underscore
words = input[:input.find("_")]
# slices input from first underscore to the end, then replaces "_" with "".
numbers = input[input.find("_"):].replace("_", "")
tgikal
  • 1,667
  • 1
  • 13
  • 27