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?

Recommended Answers

All 5 Replies

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]
"""

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? :)

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.

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

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

Thanks all for the inputs. Happy new year :)

djidjadji's solution worked great:)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.