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

Резултати

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

Пребарај: #motivational

当前筛选 #motivational清除筛选
Fluent English™

@English_easyly_learn · Post #1105 · 24.08.2018 г., 04:28

🥀🌺🥀🌺🥀🌺🥀 🌺🌾🌺🌾🥀 🥀🌺🥀 #motivational ✨The goal of life isn't to live forever. The Goal is to Create Something that will... The True love for your family and friends which is more important than wealth and privilege.✨ Have a Lovely day ahead! ☀💕💕💕🤗❤️ 🥀🌺🥀 🌺🌾🌺🌾🥀 🥀🌺🥀🌺🥀🌺🥀 @English_easyly_learn

Fluent English™

@English_easyly_learn · Post #417 · 23.03.2018 г., 16:50

Determination and Persistence This is a real life story of engineer John Roebling building the Brooklyn Bridge in New York, USA back in 1870. The bridge was completed in 1883, after 13 years. In 1883, a creative engineer named John Roebling was inspired by an idea to build a spectacular bridge connecting New York with the Long Island. However bridge building experts throughout the world thought that this was an impossible feat and told Roebling to forget the idea. It just could not be done. It was not practical. It had never been done before. Roebling could not ignore the vision he had in his mind of this bridge. He thought about it all the time and he knew deep in his heart that it could be done. He just had to share the dream with someone else. After much discussion and persuasion he managed to convince his son Washington, an up and coming engineer, that the bridge in fact could be built. Working together for the first time, the father and son developed concepts of how it could be accomplished and how the obstacles could be overcome. With great excitement and inspiration, and the headiness of a wild challenge before them, they hired their crew and began to build their dream bridge. The project started well, but when it was only a few months underway a tragic accident on the site took the life of John Roebling. Washington was also injured and left with a certain amount of brain damage, which resulted in him not being able to talk or walk. “We told them so.” “Crazy men and their crazy dreams.” “It’s foolish to chase wild visions.” Everyone had a negative comment to make and felt that the project should be scrapped since the Roeblings were the only ones who knew how the bridge could be built. In spite of his handicap Washington was never discouraged and still had a burning desire to complete the bridge and his mind was still as sharp as ever. He tried to inspire and pass on his enthusiasm to some of his friends, but they were too daunted by the task. As he lay on his bed in his hospital room, with the sunlight streaming through the windows, a gentle breeze blew the flimsy white curtains apart and he was able to see the sky and the tops of the trees outside for just a moment. It seemed that there was a message for him not to give up. Suddenly an idea hit him. All he could do was move one finger and he decided to make the best use of it. By moving this, he slowly developed a code of communication with his wife. He touched his wife’s arm with that finger, indicating to her that he wanted her to call the engineers again. Then he used the same method of tapping her arm to tell the engineers what to do. It seemed foolish but the project was under way again. For 13 years Washington tapped out his instructions with his finger on his wife’s arm, until the bridge was finally completed. Today the spectacular Brooklyn Bridge stands in all its glory as a tribute to the triumph of one man’s indomitable spirit and his determination not to be defeated by circumstances. It is also a tribute to the engineers and their team work, and to their faith in a man who was considered mad by half the world. It stands too as a tangible monument to the love and devotion of his wife who for 13 long years patiently decoded the messages of her husband and told the engineers what to do. Perhaps this is one of the best examples of a never-say-die attitude that overcomes a terrible physical handicap and achieves an impossible goal. Often when we face obstacles in our day-to-day life, our hurdles seem very small in comparison to what many others have to face. The Brooklyn Bridge shows us that dreams that seem impossible can be realised with determination and persistence, no matter what the odds are. #Motivational

12
ПретходнаСтраница 1 од 2Следна