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

Резултати

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

Пребарај: #ramadanchallenge

当前筛选 #ramadanchallenge清除筛选
WESTER School

@wester_uz · Post #3561 · 11.03.2025 г., 00:00

#RamadanChallenge Lesson 2:🎬 📌Listening: Types of Listening Questions Part 1 and Part 2 👨‍🏫 Speaker: Mr. SaidIslom - Overall: 8.5 (Listening:9.0) 📆 Date: 11.03 ⏰ Time: 06:00 Venue: 📌@westerschool_IELTS

Doniyor Olimjonov English | IELTS

@doniyorieltss · Post #1227 · 24.03.2023 г., 11:15

Many governments think that economic progress is their most important goal. Some people, however, think that other types of progress are equally important for a country. Discuss both these views and give your own opinion. It goes without saying that for a nation to flourish its economy needs to be robust, which may lead many authorities to believe that developments in this field should be their sole priority. However, I believe that there are other, possibly more important, aspects to consider. The natural instinct, when a nation is on the brink of a development or recession, is to question its economic soundness. After all, it is wealth that decides a country's fate in most cases. Take the UAE, a previously desolate dessert that is currently home to hundreds of thousands of high-rise buildings. If it hadn't been for its rich natural resources, it wouldn't have gone from abject 'nothingness' to what is now known as the richest nation in the world. In addition to its affluency, this nation is also renowned for its rich culture, which could be explained by the fact that it is a mainstream tourist destination. People from all backgrounds flock to this place in search of a better life, making it all the more popular. Thus, it is safe to say that the economy should, in fact, get a lot of the attention. But it would be unfair if the economy alone received all the credit for a nationwide success. There are usually other rather obscure sectors that inevitably spotlight economic developments as being responsible for any type of improvement in a country. Without a healthy population, for example, it is almost impossible for a society to exist, let alone thrive. One such example is Africa where, despite its rich resources, sickness and poverty run rampant. The economy doesn't signify at this point, as all the existing resources are squandered on treating the ever-increasing diseases. Education plays another important role in this regard. Having quality or poor education can mark the difference between a bright and a grim future for young people that will one day contribute to the national workforce. In other words, it is schools where any type of development begins. Economic strides are certainly essential — it is thanks to them that a country can compete with its counterparts in wealth and power. However, there won't be an economy to boost unless other types of progress, such as the medical and educational ones, receive the same level of attention, if not more. After all, these are the stepping stones to improved economy, which is the path to a better future. #MyWriting#RamadanChallenge @ieltsulugbeks

Doniyor Olimjonov English | IELTS

@doniyorieltss · Post #1220 · 23.03.2023 г., 02:44

#WritingTask2#Economy#RamadanChallenge Many governments think that economic progress is their most important goal. Some people, however, think that other types of progress are equally important for a country. Discuss both these views and give your own opinion. I will soon send my plan and sample answers for this task. @ieltsulugbeks