Заметка начинающим, которые часто сталкиваются с подобной непоняткой.
Ситуация следующая, есть список файлов:
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
🚗💨Manhart Unleashes 200+ Extra Horses on the Toyota Supra!🏎️✨
The stock 3.0L inline-six engine of the Toyota Supra packs a punch with 340 hp. But the tuning experts at Manhart have taken it to the next level, boosting it to an impressive 550 hp and a whopping 770 Nm of torque! ⚡️🔧
But that’s not all! The stunning coupe also features:
- Eye-catching aerodynamic body kit 🛠️
- Re-tuned suspension for enhanced performance 🏁
- New wheels for that perfect look! 🖤
🛒 Individual parts available:
- Engine upgrade: €11,999
- New exhaust system: €5,050
- Body kit: €13,500
- Wheels: €3,070 per set
- Coilovers: €3,100 per set
#Manhart#ToyotaSupra#Tuning#CarEnthusiast#PerformanceUpgrade#CarLovers#Auto
🚗✨ Introducing the updated Volvo XC90! ✨🚗
After nearly a decade, the XC90 has received a stunning makeover with a refreshed exterior featuring new headlights, grille, and bumpers. Plus, enjoy an enhanced suspension and a modern media system with a larger screen! 📱🔊
This new XC90 will only be available with hybrid powertrains based on gasoline engines, as the company has phased out diesel options. ⚡️🚫
🔋 The plug-in hybrid XC90 offers an impressive electric range of about 70 km, with a total driving range of 800 km! Meanwhile, mild-hybrid versions with a 48-volt starter-generator reduce fuel consumption by 15%. 🌍💚
#VolvoXC90#Hybrid#Sustainability#Innovation#CarLovers#NewRelease#Auto
🚗💨 Exciting News from Dodge! 💨🚗
Introducing the new 3.0L Hurricane Inline-Six Engine!🌪️✨
Available in two powerful options:
- 🔥 426 hp for just $10,495
- ⚡️ 558 hp for $13,745
And that's not all! A third variant boasting around 1000 hp is on the way! 🚀💯
These engines are set to replace the legendary V8 HEMI. Get ready for a thrilling ride! 🏁🔥
#Dodge#HurricaneEngine#Power#Innovation#V8HEMI#CarLovers#Automotive
🚗💨Ferrari Unveils the F80: A New Super Hybrid Rivaling McLaren W1!💨🚗
Introducing the most powerful road model in Ferrari's history! 🔥🏎️
🔴 Instead of a V12, it features a Le Mans-inspired V6 3.0 with hybrid technology.
🔴 Produces a staggering 900 hp, revving up to 9000 RPM!
🔴 Combined output with electric motors (developed by Ferrari) reaches an astonishing 1200 hp!
🔴 0-100 km/h in just 2.15 seconds!
🔴 0-200 km/h in only 5.75 seconds!
🔴 Top speed of 350 km/h!
🔴 800-volt electrical architecture for ultimate performance!
🔴 Dry weight of 1525 kg!
🔴 Monocoque made from carbon fiber, with aluminum front and rear subframes!
The F80 features a two-seat configuration, with a driver-focused cockpit, dubbed "1+." 🏁👤
Its retro design pays homage to the legendary Daytona and F40, generating a whopping ton of downforce at 250 km/h! 🌬️✨
🚀Availability: Late 2025
💰Starting Price: €3.6 million
🔢 Only 799 units will be produced!
#FerrariF80#SuperHybrid#Hypercar#Ferrari#McLarenW1#CarLovers#Auto
When you want your car to be as cozy as your living room 🛋️🚗
#Satisfying#Transformation#DIY#Craftsmanship#UniqueRides#CarLovers#ViralVideo#Reels#FacebookWatch#AmazingCars
Full video 👇
https://www.facebook.com/share/r/1Dg1M4jKCs/
🚗💨 Introducing the all-new Brabus Mercedes-AMG S-Class! 🌟
This stunning beast boasts a jaw-dropping 1000 horsepower and a mind-blowing 1820 Nm of torque! 🔥💪
🔧 Under the hood, the 4.5-liter V8 has been meticulously upgraded with a custom turbo system, new pistons, and a fresh ECU tune. Get ready for an exhilarating driving experience! 🏎️💨
✨ The exterior features aggressive carbon aerodynamic elements and is finished in a unique shade of grey, perfectly complemented by 22-inch forged wheels. 😍🖤
🛋️ Inside, luxury meets style with exquisite grey quilted leather upholstery that takes comfort to the next level.
#Brabus#MercedesAMG#SClass#LuxuryCars#CarEnthusiast#1000HP#Performance#AutomotiveDesign#CarLovers#Auto🚘✨
🚀Yangwang U9 Sets New Record!🚀
The incredible Yangwang U9 by BYD has reached a jaw-dropping speed of 391.94 km/h! 🏎️💨 This marks a new record for Chinese cars, surpassing its previous achievement by 17 km/h and far exceeding its official top speed of 309 km/h.
To achieve this feat, the 1306-horsepower hypercar underwent significant upgrades, including enhanced aerodynamics, lightweight wheels with track tires, and a software reprogramming. 🔧✨
#YangwangU9#BYD#Hypercar#SpeedRecord#AutomotiveInnovation#CarLovers#Performance#ChineseAutomobile#Auto
🚗💨 Introducing the Naran Hypercar: The Ultimate Powerhouse! 🌟
Get ready for the unveiling of the Naran Hypercar in the UK this August! 🇬🇧 With a staggering 1000 horsepower, this beast promises to be the fastest four-seater car in the world, powered by a traditional internal combustion engine—no electric enhancements! ⚡️❌
Only 39 units will be produced, making it an exclusive masterpiece! 🎨✨
Under the hood, it features a 5.0-liter twin-turbo V8, derived from BMW's impressive 4.4-liter engine. 🏎️💥 And yes, it comes with full-wheel drive for that ultimate driving experience! 🌍🚀
#NaranHypercar#CarEnthusiasts#AutomotiveExcellence#V8Power#Hypercar#FastestCar#LuxuryCars#CarLovers#InnovativeEngineering
🚗✨ Introducing the all-new AC Cobra GT Coupe! 🌟
For the first time in history, this iconic sports car is getting a hardtop version, and it's set to be produced in series! 🏁💨
With stunning carbon body panels, the Coupe is not only beautiful but also powerful! 💪🔥 Choose between two roaring V8 engines: 565 or 730 horsepower!
Starting at just £325,000, this masterpiece is ready to hit the roads! 💷🚀
#ACCobra#SportsCar#CarEnthusiast#LuxuryAutomobile#V8Power#CobraGT#CarLovers#IconicDesign#AutomotiveExcellence