I have a set of strings as below:


I want everything after the ':' to be discarded. i.e., i just want a list of what preceeds ':' (4,5,6,7,22,.................)

How can this be done?

Edited 5 Years Ago by novice20: n/a

Use a regular expression (module re)

import re
digits_colon_re = re.compile(r"(?P<digits>\d+)\:")

data = """
""".strip().replace("\n", "").split(",")

print([int(match.group("digits")) for match in (digits_colon_re.search(s) for s in data)])

""" my output --->
[4, 5, 6, 7, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31]

Edited 5 Years Ago by Gribouillis: n/a

Happy Newyear.
This is your newyear gift.


d=[c for c in str.split(",")]
print([int(f.split(":")[0]) for f in d ])

##out Put
[4, 5, 6, 7, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31]

And if you like it. you can upvote me a lil ok? :)

Edited 5 Years Ago by richieking: n/a

My fatherly advice, do not name a variable str since str is also a built-in Python function name. This would get you into trouble if you ever want to use the str function later in your code.

Edited 5 Years Ago by vegaseat: n/a

It can all be done in one call to re.findall() or re.finditer()

mynums = [int(x) for x in re.findall('\d+(?=:)',dd)]
nice work

Thanks all for the inputs. Happy new year :)

djidjadji's solution worked great:)

This question has already been answered. Start a new discussion instead.