Home > Mobile >  Replace characters in specific locations in strings inside lists
Replace characters in specific locations in strings inside lists

Time:02-15

Very new to Python/programming, trying to create a "grocery list generator" as a practice project.

I created a bunch of meal variables with their ingredients in a list, then to organise that list in a specific (albeit probably super inefficient) way with vegetables at the top I've added a numerical value at the start of each string. It looks like this -

meal = ["07.ingredient1", "02.ingredient2", "05.ingredient3"]

It organises, prints, and writes how I want it to, but now I want to remove the first three characters (the numbers) from each string in the list before I write it to my text file.

So far my final bit of code looks like this - Screenshot of final block of code

Have tried a few different things between the '.sort' and 'with open' like replace, strip, range and some other things but can't get them to work.

My next stop was trying something like this, but can't figure it out -

for item in groceries[1:]
    str(groceries(range99)).replace('')

Thanks heaps for your help!

CodePudding user response:

for item in groceries:
    shopping_list.write(item[3:]   '\n')

CodePudding user response:

Instead of replacing you can just take a substring.

groceries = [g[3:] for g in groceries]

CodePudding user response:

Depending on your general programming knowledge, this solution is maybe a bit enhanced, but regular expressions would be another alternative.

import re
pattern = re.compile(r"\d \.\s*(\w )")
for item in groceries:
    ingredient = pattern.findall(item)[0]

\d means any digit (0-9), means "at least one", \. matches ".", \s is whitespace and * means "0 or more" and \w is any word character (a-z, A-Z, 0-9).

This would also match things like

groceries = ["1.   sugar", "0110.salt", "10. tomatoes"]

CodePudding user response:

>>> meal = ["07.ingredient1", "02.ingredient2", "05.ingredient3"]
>>> myarr = [i[3:] for i in meal]
>>> print(myarr)
['ingredient1', 'ingredient2', 'ingredient3']
  • Related