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

Резултати

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

Пребарај: #deploy

当前筛选 #deploy清除筛选
Code 𝕏 Botz

@CodeXBotz · Post #1328 · 05.01.2022 г., 14:18

#Deploy Deploy file share bot using telegram Bot Just login with with your heroku account via the bot and you can deploy file sharing bot https://telegram.dog/XTZ_HerokuBot?start=Q29kZVhCb3R6L0ZpbGUtU2hhcmluZy1Cb3QgbWFpbg Thanks to @subin_works

Hashtags

Valisher Botirov | Development

@valisherbotirov · Post #229 · 03.04.2024 г., 19:01

Dasturni front qismini server qo'yishda dasturchilar orasida bepul bo'lgani uchun Netlify va Vercel serverlaridan foydalanish keng tarqalgan. Bulardan foydalanganda nested pagelarda yuqoridagi rasmda ko'rsatilgandek error kelib chiqadi. Buni oldini olish uchun proyektingizga quyidagi kodlarni qo'shishingiz kerak bo'ladi. Agar proyekt Netlifyda bo'lsa netlify.toml file yaratib ichiga [[redirects]] from = "/*" to="/index.html" status = 200 larni qo'shish kerak. Agar Vercelga qo'yilgan bo'lsa unda vercel.json file yaratib ichiga { "routes": [{ "src": "/[^.]+", "dest": "/", "status": 200 }] } larni qo'shish kerak. Shunda nested pagelarda error bermaydi. #frontend#deploy#avoid_error ☑️@valisherbotirov

American Оbserver

@american_observer · Post #5162 · 18.02.2026 г., 12:59

Russia Is Up To Deploy Navy To Protect Vessels from the West A senior Russian official has said Moscow could deploy its navy to protect Russian-linked vessels from potential European seizures, raising the prospect of retaliatory action against European shipping as pressure on the Kremlin’s so-called shadow fleet intensifies. Nikolai Patrushev, a former FSB director who heads Russia’s maritime board, said on Tuesday that the country’s navy should be ready to counter what he described as “western piracy”. Patrushev added that any attempt to impose a maritime blockade on Russia would be illegal under international law, claiming that the EU’s use of the term “shadow fleet” had no legal basis. His comments came as senior Ukrainian and Russian officials are met in Geneva on Tuesday for the latest round of high-stakes talks brokered by the Trump administration, as the fourth anniversary of Moscow’s full-scale invasion of Ukraine draws near. Ahead of the talks, Russia carried out heavy airstrikes overnight across swathes of Ukraine, inflicting severe damage to the power network in the southern port city of Odesa, which Zelensky said left tens of thousands without heat and water. The term shadow fleet refers to an estimated 1,500 ageing or lightly regulated oil tankers operating under opaque ownership structures to help Russia export crude to buyers such as China and India while circumventing western sanctions. More than 600 vessels have been targeted by sanctions from the EU, UK and US. These measures have helped curb Russian oil revenues. Despite growing political pressure, European governments have struggled to develop a coherent legal mechanism for physically stopping or confiscating the ships, relying instead on sanctions, insurance restrictions and inspections. Western allies have warned that vessels lacking proper documentation may be treated as stateless ships, potentially widening the scope for intervention at sea. The British defence secretary, John Healey, met European counterparts on the sidelines of the Munich Security Conference at the weekend to discuss possible moves to seize tankers linked to Russia’s shadow fleet. Earlier this year, the French navy briefly intercepted a tanker suspected of operating within the shadow fleet before allowing it to continue its journey. The US has, in recent months, moved to physically interdict and seize several tankers linked to shadow fleets carrying sanctioned oil from Russia, Venezuela and Iran. Patrushev’s comments, however, appeared to focus primarily on Europe, suggesting the Kremlin is wary of escalating tensions with Washington while delicate negotiations over Ukraine continue. #russia#deploy#navy#protect#vessels#patrushev 📱American Оbserver - Stay up to date on all important events 🇺🇸

djangoproject

@djangoproject · Post #513 · 30.11.2017 г., 22:00

#AI#Artificial_Intelligence #AJAX #aiohttp #Anaconda #AngularJS #API #Atom #AWS #asyncio (#Asynchronous) #audio #automated_testing #automation #atexit #BeeWare #Big_Data #bitcoin #blockchain #Bluemix #Brython #button #Celery #client #class #classmethod #concurrency #Coroutine #cron #CSS #curl #data_analysis #data_mining #data_processing #database #Deep_Learning#deep_learning #Debian #decorator #deploy #dict #dispatch #django #django_cms #Django_REST_Framework #dropdownbox #Docker #event #Firefox #Flask #form #functions #Generator #GeoDjango #git #Google #GPU #GUI #Gym #host #HTML #httplib #learn #Image_processing #intelligence #input #Instagram #IOT #iPython #Jupyter #lambda #learn #License #Linux #lists #machine_learning #Magenta #map #Matplotlib #Metaprogramming #Micro_services #Micropython #mind #monitoring #MongoDB #modules #Mozilla #Multipart #multi_touch_apps #multiprocessing #Nodes #NoSQL #numeric_computation #numerical #NumPy #network #neural_network #OAuth #object_serialization #OCR #overloading #package #parallel #pipeline #protocols #PostGIS #pyAudioAnalysis #pycon #Pyflakes #PyInstaller #PyPI #PyQt #PySide #PyTorch #pytest #python #Pyvideo_archives #Qt #Raspberry_Pi #React #Redis #random #request #Regular_Expressions (#re) #REST #RSS #satellite #scikit_learn #SciPy #scrapy #searching #selectbox #Selenium #serialization #server #sessions #single_responsibility_principle #socket #Spark #str #submit #task #telegram #template #TensorFlow #test #text_boxes #text #tuples #unicode #Universe #Unix #unit_test #urllib #upload #uWSGI #Web #WSGI