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

Резултати

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

Пребарај: #astrophysics

当前筛选 #astrophysics清除筛选
Interesting Planet 🌍

@interesting_planet_facts · Post #716 · 09.09.2025 г., 13:22

🌎 Lurking in deep space, “dark matter” makes up about 27% of the universe, yet it remains invisible. Scientists infer its existence by observing gravity’s effects—like stars swirling faster than visible matter alone predicts. Its true nature is still unknown, but it outweighs all regular matter combined. ✨ #space⚡#astrophysics⚡#mystery 👉subscribe Interesting Planet ​

Interesting Planet 🌍

@interesting_planet_facts · Post #1236 · 19.01.2026 г., 12:11

🌎 Mysterious dark matter makes up about 27% of the universe, but it does not emit or absorb light, making it invisible. Scientists detect dark matter only through its gravitational effects on galaxies and galaxy clusters. The leading candidates for dark matter particles are called WIMPs—Weakly Interacting Massive Particles. ✨ #space⚡#universe⚡#astrophysics 👉subscribe Interesting Planet 👉more Channels ​

Interesting Planet 🌍

@interesting_planet_facts · Post #1122 · 12.12.2025 г., 12:11

🌎 Gamma-ray bursts are the most energetic explosions in the universe, releasing in seconds as much energy as the Sun emits over its entire 10-billion-year lifespan. They are detected by satellites as brief flashes of gamma radiation, and are thought to result from collapsing massive stars or merging neutron stars. ✨ #space⚡#gamma⚡#astrophysics 👉subscribe Interesting Planet 👉more Channels ​

Universe Mysteries 🪐

@cosmomyst · Post #292 · 18.09.2025 г., 16:11

🪐 In the spiral galaxy NGC 4993, scientists observed a gamma-ray burst, GRB 170817A, that arrived just 1.7 seconds after gravitational waves from the merger of two neutron stars—ultra-dense stellar remnants. This remarkable event marked the first time both gravitational waves and a gamma-ray burst were detected from the same source, giving astronomers an unprecedented, multi-messenger view of a cosmic collision. ✨ #gamma⚡#astrophysics⚡#neutronstars⚡#nasa⚡#galaxy⚡#stars⚡#astronomy⚡#universe⚡#cosmos⚡#space 👉subscribe Universe Mysteries ​

Universe Mysteries 🪐

@cosmomyst · Post #563 · 17.12.2025 г., 12:21

🪐 In 2022, the Event Horizon Telescope captured the first radio image of the supermassive black hole at the center of our galaxy, Sagittarius A*, revealing a glowing ring of hot gas swirling around the event horizon—the point beyond which nothing can escape. This image confirmed decades of theory about black holes and showed that matter falling in forms a bright, lopsided halo just outside the black hole’s shadow, unlocking new clues about how these cosmic giants really behave. ✨ #blackholes⚡#SagittariusA⚡#astrophysics⚡#nasa⚡#galaxy⚡#stars⚡#astronomy⚡#universe⚡#cosmos⚡#space 👉subscribe Universe Mysteries 👉more Channels ​

Universe Mysteries 🪐

@cosmomyst · Post #485 · 08.11.2025 г., 12:21

🪐 The star HE 0107-5240, found in the constellation Phoenix, is one of the most metal-poor stars ever discovered, meaning it contains almost no elements heavier than hydrogen and helium. This rare "primordial" star likely formed from the material left over after the very first stars died, making it an ancient relic that helps scientists study the universe's earliest generations of stars. ✨ #unusualstars⚡#primordialstars⚡#astrophysics⚡#nasa⚡#galaxy⚡#stars⚡#astronomy⚡#universe⚡#cosmos⚡#space 👉subscribe Universe Mysteries 👉more Channels ​

Universe Mysteries 🪐

@cosmomyst · Post #606 · 06.01.2026 г., 22:21

🪐 The spiral galaxy Messier 83 has hosted more recorded gamma-ray bursts than almost any spiral galaxy nearby, becoming a hotspot for these mysterious explosions. Gamma-ray bursts are split-second flashes of the universe’s most energetic light, and their frequent appearance in Messier 83 helps scientists study how massive stars can end their lives in extreme, spectacular fashion. ✨ #Messier83⚡#gamma⚡#astrophysics⚡#nasa⚡#galaxy⚡#stars⚡#astronomy⚡#universe⚡#cosmos⚡#space 👉subscribe Universe Mysteries 👉more Channels ​

Universe Mysteries 🪐

@cosmomyst · Post #331 · 26.09.2025 г., 12:21

🪐 The pulsar PSR J0437−4715, located about 500 light-years away in the constellation Pictor, spins nearly 174 times per second and is famous for its near-perfect "cosmic clock" precision. This ultra-stable pulsar allows astronomers to test the fundamental laws of physics and even hunt for elusive gravitational waves by tracking the tiny variations in its radio pulses over many years. ✨ #pulsars⚡#Pictor⚡#astrophysics⚡#nasa⚡#galaxy⚡#stars⚡#astronomy⚡#universe⚡#cosmos⚡#space 👉subscribe Universe Mysteries 👉more Channels ​

What If The Universe DID NOT Start With The Big Bang? @PBS Space Time 👉 Head to https://brilliant.org/spacetime/ for a 30-day free trial + 20% off your annual subscription #YouTube#liked#Black_Holes#Black_Hole#Black_Hole_Physics#Space#Outer_Space#Physics#Astrophysics#Quantum_Mechanics#Space_Physics#PBS#Space_Time#Time#PBS_Space_Time#Matt_O_Dowd#Einstein#Einsteinian_Physics#General_Relativity#Special_Relativity#Dark_Energy#Dark_Matter#The_Universe#Math#Science_Fiction#Calculus#Maths#Holographic_Universe#Holographic_Principle#Rare_Earth#Anthropic_Principle#Weak_Anthropic_Principle#Strong_Anthropic_Principle