Hi...

I have a set of strings as below:

4:14.4-17M,5:14.4-2e13M,6:14.4-4e9M,7:14.4-8e,22:28.4-35M,23:28.4-2e30M,24:28.4-4e26M,25:28.4-8e18M,26:28.4-16e2M,27:28.4-18e,28:14.16-36M,29:14.16-2e32M,30:14.16-4e28M,31:14.16-8e20M

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 = """
4:14.4-17M,5:14.4-2e13M,6:14.4-4e9M,7:14.4-8e,22:28.4-35M,23:28.4-2e30M,
24:28.4-4e26M,25:28.4-8e18M,26:28.4-16e2M,27:28.4-18e,28:14.16-36M,29:14.16-2e32M,
30:14.16-4e28M,31:14.16-8e20M
""".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.

str="4:14.4-17M,5:14.4-2e13M,6:14.4-4e9M,7:14.4-8e,22:28.4-35M,\
23:28.4-2e30M,24:28.4-4e26M,25:28.4-8e18M,26:28.4-16e2M,27:28.4-18e,\
28:14.16-36M,29:14.16-2e32M,30:14.16-4e28M,31:14.16-8e20M"

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)]
Comments
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.