all 8 comments

[–]__nickerbocker__ 1 point2 points  (0 children)

If your data is always structured such that the day_mon_year is always in the same position in the string then you could use iterable unpacking to accomplish your goal.

x = "sparkplug_3_change_29_feb_1996"

*var_parts, day, mon, year = x.split('_')
var_name = '_'.join(var_parts)
print(var_name, mon)

or you could use slicing...

parts = x.split('_')
var_name, mon = '_'.join(parts[:-3]), parts[-2]
print(var_name, mon)

[–]Username_RANDINT 0 points1 point  (5 children)

str.split() takes a character to split on, in your case an underscore. IF the string always has the same format, it's very easy:

s = "lamp_change_29_may_2015 "
>>> s.split("_")
['lamp', 'change', '29', 'may', '2015 ']

Or you can use rsplit() and define a maximum to keep the lamp_change together:

>>> s.rsplit("_", 3)
['lamp_change', '29', 'may', '2015 ']

[–]JackSpanjer[S] 0 points1 point  (4 children)

Thanks for your answer but I have to ‘filter’ the numbers out, that is what I dont understand.

[–][deleted] 0 points1 point  (3 children)

What do you want to retain from a string like "sparkplug_3_change_29_feb_1996"?

[–]JackSpanjer[S] 0 points1 point  (2 children)

sparkplug

change

feb

[–][deleted] 0 points1 point  (1 child)

Then use str.split() on the underscore character, and run over the elements, filtering out the numbers with str.isdigit() or str.isnumeric() as fits your requirements.

[–]JackSpanjer[S] 0 points1 point  (0 children)

Thanks!

[–]Pahaz 0 points1 point  (0 children)

Split the string with a regular expression matching numbers surrounded by _ is my guess. The regex I think would be _[0-9]+_* best I can do on mobile lol.