Pythonizer
Pythonizer

Reputation: 1194

removing a pattern from a list items in python

My list has 15 items, all of them contains the word '_new' in the end. So I want to create folders with names of the items without '_new' in it. How to do it?

Upvotes: 1

Views: 5903

Answers (3)

Yogesh dwivedi Geitpl
Yogesh dwivedi Geitpl

Reputation: 4462

Use strip method with list comprehension to remove "_new":

import os
path = r"C:\Program Files\mypath"
[os.makedirs(os.path.join(path,str(name.strip("_new"))) for name in name_list if os.path.exists(path)]

Upvotes: 0

Jon Clements
Jon Clements

Reputation: 142206

I'll go for the regex then:

import re
new = [re.sub('_new$', '', fname) for fname in your_list]

However you correct your name, you'll want to use os.mkdir to create it.

Upvotes: 1

Martijn Pieters
Martijn Pieters

Reputation: 1123510

Use a list comprehension to remove the last 4 characters:

[name[:-4] for name in list_of_names]

If only some of the names contain _new at the end, use a conditional expression:

[name[:-4] if name.endswith('_new') else name for name in list_of_names]

Upvotes: 8

Related Questions