0

I have a list:

data = ["data 01", "data 02", "data 03"]

I want to check if each element in list contain the string "data", and also add the text after data (e.g 01, 02, 03) to another list. Below is the code I have, but I find it to be inefficient.

data_2 = []

for item in data:
    if ("data" in item):
        data_2.append(item.replace("data", "").strip())

Is there a way to check

if item == "data {}"

Where {} is a numerical variable. As a precaution to having an item in data list like ["no data"], where the string "no" gets added by mistake?

2
  • Use item.startswith('data') Commented Jun 17, 2020 at 21:10
  • There are numerous ways, but I would say that Python re is probably the way to go. Commented Jun 17, 2020 at 21:12

2 Answers 2

1

You can use a list comprehension:

data = ["data 01", "data 02", "data 03"]
d = [s.split('data ',1)[1] for s in data if 'data' in s and s.split('data ',1)[1].isdigit()]
print(d)

Output:

['01', '02', '03']
Sign up to request clarification or add additional context in comments.

1 Comment

This still doesn't check that there's a number after data. Did you miss that part of the question?
0

use a regular expression to test that it matches the whole pattern.

import re

for item in data:
    result = re.match(r'data (\d+)$')
    if result:
        data_2.append(result.group(1))

result.group(1) will contain the number that was captured by (\d+)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.