TGTGInsighttelegram intelligenceLIVE / telegram public index
← Python Заметки

TGINSIGHT SIMILAR POSTS

Најди сличен содржај

Изворен канал @pythonotes · Post #22 · 19 јан.

Заметка начинающим, которые часто сталкиваются с подобной непоняткой. Ситуация следующая, есть список файлов: 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

Hashtags

Резултати

Пронајдени 7 слични објави

Пребарај: #hybridpower

当前筛选 #hybridpower清除筛选
Auto Life

@revheadcrypto · Post #432 · 04.09.2024 г., 15:08

🚗✨ Exciting News! The new Bentley Flying Spur is set to debut on September 10th! 🎉 This stunning sedan will feature the same V8 hybrid powertrain as the recently launched Continental GT. According to Bentley, it will be the "most powerful, dynamic, and economical four-door car in Bentley's 105-year history." 💪🌍 Stay tuned for more updates! #BentleyFlyingSpur#LuxuryCars#HybridPower#Bentley#Auto

Auto Life

@revheadcrypto · Post #378 · 23.08.2024 г., 22:34

🚗✨ Exciting news! The updated Volvo XC90 is set to be unveiled on September 4th! 🌟 🔋 This refreshed model will feature a hybrid powertrain, ensuring it remains relevant until the brand transitions fully to electric vehicles by the end of the decade. ⚡️ Stay tuned for more updates! #VolvoXC90#HybridPower#SustainableDriving#CarLaunch#Auto

Auto Life

@revheadcrypto · Post #159 · 23.07.2024 г., 18:27

🚗Introducing the upcoming McLaren P18! 🔥 Exciting news - this flagship supercar is set to be a 1000-horsepower all-wheel-drive hybrid! Only 399 lucky owners will get their hands on this beauty. 😍 Stay tuned for more details as clients have only seen a scale model of the design so far. #McLarenP18#Supercar#HybridPower#AllWheelDrive#Auto🏁🔋🌟

Auto Life

@revheadcrypto · Post #531 · 27.09.2024 г., 10:43

🚗✨ Exciting news from McLaren! On October 6th, we might witness the unveiling of a brand new model that continues the legendary "1" lineage! 🌟 In a teaser video featuring the iconic F1 and P1, the date at the end hints at a thrilling reveal. 🔥 This hybrid supercar is set to deliver around 1000 hp, powered by a stunning V8 engine. 💪💨 Get ready for the next chapter in automotive excellence! #McLaren#Supercar#HybridPower#ComingSoon#October6#Auto

Auto Life

@revheadcrypto · Post #585 · 17.10.2024 г., 05:59

🚗✨Introducing the Updated Audi A3 Hatchback: A Powerful Hybrid!✨🚗 ⚙️ The heart of this beauty is the new 1.5 TFSI evo2 engine, replacing the previous 1.4-liter four-cylinder. With an increased compression ratio and higher fuel injection pressure, it's ready to impress! 💥 🔋 Coupled with a 116-hp electric motor, the 40 TFSI e variant produces a total of 204 hp and 350 Nm of torque, accelerating from 0 to 100 km/h in just 7.4 seconds! 🚀 Max speed? A thrilling 225 km/h! 🌟 🔥 For those craving more power, the 45 TFSI e variant boasts 272 hp and 400 Nm, hitting 100 km/h in just 6.3 seconds and a top speed of 237 km/h! 🏁💨 🛒 Orders are now open starting at €44,200! #AudiA3#HybridPower#Innovation#LuxuryCars#CarEnthusiast#Performance#AudiLife#Auto🌍💚

Auto Life

@revheadcrypto · Post #530 · 26.09.2024 г., 13:57

🚗✨ Exciting News for BMW Fans! The new BMW 5 Series Touring is here with electrified powertrains! ⚡️ Starting off, the lineup features a mild-hybrid 2.0L diesel engine. Now, it’s joined by a petrol alternative: a 2.0L engine paired with a 48V starter-generator, delivering 208 hp and 330 Nm. 🔥 Introducing the BMW 550e Touring: a full hybrid powerhouse with a 6-cylinder engine and an integrated electric motor in the 8-speed transmission, boasting an impressive 489 hp! 💪 On electric power alone, it can travel up to 90 km, reaching 0-100 km/h in just 4.4 seconds! ⏱️ And don’t miss the BMW i5 xDrive40 Touring! This all-electric beauty packs dual motors that deliver a total of 394 hp and 590 Nm. ⚡️🌍 #BMW#5Series#ElectricDriving#HybridPower#CarEnthusiast#LuxuryCars#Innovation#Sports🚘💚

Auto Life

@revheadcrypto · Post #483 · 12.09.2024 г., 15:14

🚗✨Introducing the BMW M5 Touring with M Performance Parts!🏁 BMW has unveiled stunning images of the new M5 Touring, now available with exclusive M Performance Parts! 🎉 This five-door beauty can be equipped with new aerodynamic body enhancements and a stylish alternative set of floor mats for the interior. Plus, an expanded range of accessories is now at your fingertips! 🛠️💎 Under the hood, the M5 Touring boasts a powerful hybrid powertrain delivering an impressive 727 hp and 1000 Nm of torque, allowing it to sprint from 0 to 100 km/h in just 3.6 seconds! ⚡️🚀 For those seeking even more thrill, the speed limiter can be raised to an exhilarating 305 km/h for an additional fee! 🏎️💨 #BMW#M5Touring#MPerformance#HybridPower#LuxuryCars#CarEnthusiasts#PerformanceParts#FastCars#Auto🚘🔥