Заметка начинающим, которые часто сталкиваются с подобной непоняткой.
Ситуация следующая, есть список файлов:
names = [
'image.bmp',
'second.txt.bkp',
'data.db',
'.config.cfg',
'file.ext.bkp'
]
И мы хотим убрать у них окончание ".bkp".
Не знаю зачем, пример довольно надуманный) Но суть он показывает, а это главное.
Те, кто еще не очень знаком с библиотекой os.path или pathlib, вероятно решат обработать имена как строки. И тут вполне подойдет метод строки strip().
Что делает этот метод? Он отрезает указанные символы по обеим сторонам строки. Если ничего не указать, то убирает невидимые символы (пробелы, табуляции и переносы строк).
В нашем случае будет выглядеть вот так:
>>> name.strip('.bkp')
То есть просим удалить строку '.bkp' по краям имени файла, если таковая есть.
Можно применить аналогичный метод rstrip(), чтобы отрезать только справа, но для этого примера используем обычный.
>>> for name in names:
>>> print(name.strip('.bkp'))
image.bm
second.txt
data.d
config.cfg
file.ext
Хм, что-то не то с нашими именами! Что случилось??? Видим нежелательное переименование в именах, где и близко не было указанной строки '.bkp'
А дело всё в том, что данный метод ищет не указанную строку, а указанные символы, и не важно в каком порядке.
Для метода strip() строка '.bkp' это не паттерн для поискаа список символов. Потому он отрезал симовол 'p' от '.bmp' и удалил точку из файла '.config.cfg'.
Как тогда правильно заменить именно паттерн? Для начинающего можно посоветовать метод строки replace(), который как раз использует для замены указанную строку целиком. В нашем примере заменим её на пустую строку.
>>> for name in names:
>>> print(name.replace('.bkp', ''))
image.bmp
second.txt
data.db
.config.cfg
file.ext
Уже лучше, но помните, это лишь пример про strip(). Для работы с именами файлов есть способы и более "правильные", дающие однозначно верный результат. Я взял файлы только в качестве примера. Даже replase() тут может сделать не то что ожидаем.
Просто впредь будьте внимательны с этим strip().
#basic
On this #WorldFoodDay, let's prioritize nutritious, balanced meals and make healthier food choices for a stronger, disease-free future.
Good nutrition is the foundation of good health. 💪
#HealthyEating#WorldFoodDay#NCDCNigeria
Healthy Planet, Healthy You!
❗️Informative signs on “General Rules and Environmental Protection: Healthy Eating Habits” have been placed around the campus by psychologist Muslima Nabijonova and tutor Shokhrukh Obidov — reminding everyone that caring for nature starts with caring for ourselves
#GreenUniversity#EcoLifestyle#HealthyEating#Sustainability
✉️[email protected]
☎️ +998 55 512 00 77
📍Location
🌐Website | 📱Telegram | 📱Instagram | 📱LinkedIn | 🟥YouTube
Black sapote is a fruit from Mexico and Central America. When unripe, it is hard and green. When ripe, the skin is olive-green, and the inside is soft, dark brown, and creamy like chocolate pudding. It tastes sweet and mild, like chocolate but has no bitterness or caffeine. People eat it as dessert or use it in smoothies and baking. 🍫🍃
[Source]
@googlefactss#BlackSapote#TropicalFruit#HealthyEating
Pink Pasta
🍝 Ingredients:
- 300 g pasta
🍄Sauce:
- 250 g cooked beetroot 🥗
- 100 g cashew nuts 🥜
- 50 ml water 💧
- 1 tbsp soy yogurt skyr 🥛
- 1 tsp oil 🫒
- 1 tsp agave syrup 🍯
- 1 tsp salt 🧂
- 1 tsp pepper 🌶️
- 1 tsp vegetable broth 🍲
Preparation:
1. 🥄 Soak the cashews in warm water for 10 minutes, then drain. Meanwhile, cook the pasta 🍲.
2. 🥢 Dice the beetroot and blend it with the other sauce ingredients until smooth.
3. 🍳 Crumble the tofu and sauté in oil, then add the beetroot and chickpeas. Fry until golden.
4. 🍝 Mix the pasta with the sauce, add your favorite toppings, and enjoy!
#PinkPasta#VeganRecipe#HealthyEating
@dishes
High Protein Wan Tan
Ingredients:
For the dough:
- 250 g flour 🌾
- 1 tsp salt 🧂
- 100 ml warm water 💧
For the filling:
- 1 cm ginger 🫚
- 100 g soy granules 🌱
- 2 spring onions 🧅
- 2 cloves of garlic 🧄
- 3 mushrooms 🍄
- 1 carrot 🥕
- 4 tbsp soy sauce 🧴
- 1 tbsp starch 🌿
Additionally:
- oil for frying 🛢️
- 100 ml water for steaming 💦
#HighProtein#WanTan#HealthyEating#Vegan
@dishes
Jellyfish have been eaten in Asia for centuries. People eat them in China, Japan, and Southeast Asia. They are processed with salt and alum to remove water and make them crunchy. Only certain species are safe to eat. Jellyfish are low in calories and high in protein. The processing tightens proteins, giving them a firm, crunchy texture. They are often served in salads, cold dishes, or as a crunchy snack.
🦑🥗🍴
[Read more]
@googlefactss
#JellyfishFood#AsianCuisine#SeafoodFacts#HealthyEating#FoodHistory
To ripen avocados fast, put them in a brown paper bag with an apple or banana. These fruits release a gas called ethylene that helps avocados ripen quicker, usually in 1 to 3 days. Keep the bag at room temperature and check daily. Avoid the fridge until they are ripe, or they won’t ripen properly. 🥑🍌🍎@googlefactss
#AvocadoRipening#FastRipen#KitchenTips#FruitRipening#HealthyEating
Cold weather and frost make many vegetables sweeter by increasing their sugar. Collards survive down to -9°C (15°F), beets down to -7°C (20°F), and both grow well if planted in late summer. Frost may damage some leaves but helps roots taste better.
Cover plants with row covers if it gets colder than -7°C (20°F) to protect them.
🌿❄️
@googlefactss
#WinterVeggies#FrostSweetened#ColdHardy#GardeningTips#HealthyEating
High Protein Vegetable Patties
🥕 Ingredients:
- 1 small carrot 🥕
- 1 medium potato 🥔
- 1/2 bell pepper 🌶
- 1 onion 🧅
- 50 g soy granules 🌱
- 50 g corn 🌽
- 50 ml water 💧
- 100 g flour 🌾
- 1 tbsp starch ✨
- Oil for frying 🍳
Preparation:
1️⃣ Grate the carrot & potato, dice the pepper & onion, and place in a bowl 🥣
2️⃣ Soak the soybean granules in water, then add to the bowl along with the remaining ingredients and mix well 👩🍳
3️⃣ Shape the dough into patties and sauté in a pan with a little oil until golden brown 🥘
Enjoy! 😋
#HighProtein#VegetablePatties#VeganRecipe#HealthyEating#PlantBased
@dishes
High Protein Vegetable Patties
🥕 Ingredients:
- 1 small carrot 🥕
- 1 medium potato 🥔
- 1/2 bell pepper 🌶️
- 1 onion 🧅
- 50 g soy granules 🌱
- 50 g corn 🌽
- 50 ml water 💧
- 100 g flour 🌾
- 1 tbsp starch ✨
- Oil for frying 🍳
Preparation:
1️⃣ Grate the carrot & potato, dice the pepper & onion, and place in a bowl 🥣
2️⃣ Soak the soybean granules in water, then add to the bowl along with the remaining ingredients and mix well 👩🍳
3️⃣ Shape the dough into patties and sauté in a pan with a little oil until golden brown 🥘
Enjoy! 😋
#HighProtein#VegetablePatties#VeganRecipe#HealthyEating#PlantBased
@dishes
🥞High Protein Cereal Pancakes 🥞
Ingredients:
🌾 160g flour
🥛 360 ml almond drink
💪 1 tbsp protein powder (optional)
✨ 1 tsp baking powder
🍯 1 tbsp agave syrup
🍏 2 tbsp apple cider vinegar
Toppings:
🥝 5 mini kiwis
🥥 200 ml plant-based drink
🌴 1 tsp date syrup
🍒 Pomegranate seeds
Preparation:
1️⃣ Mix all ingredients for the pancakes.
2️⃣ Fry a thumb-sized portion of dough over medium heat with a little oil.
3️⃣ Enjoy with your delicious toppings! 😋
---
#HealthyEating#HighProteinPancakes#VeganBreakfast#PancakeLovers@dishes
@dishes