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 слични објави

Пребарај: #term

当前筛选 #term清除筛选
Language Trivia 🤔

@languagetrivia · Post #563 · 03.01.2025 г., 10:14

Which linguistic term, named after an Oxford professor, describes the humorous mistake of swapping the initial sounds of two words, as in ➖“belly jeans” instead of “jelly beans” ➖“our queer old dean” instead of “our dear old queen” A) Malapropism B) Anagram C) Palindrome D) Spoonerism @languagetrivia#term

Hashtags

Language Trivia 🤔

@languagetrivia · Post #473 · 12.12.2024 г., 15:17

😮Did you know that some words can mean their own opposite? ☯️ There's a cool linguistic phenomenon where certain words have two opposing meanings. These words are like linguistic chameleons, adapting to completely different interpretations in different scenarios! Here are 5 examples of such words: ➖Sanction ➖To officially approve or permit something: The government sanctioned the new policy. ➖To punish or penalize: The country faced sanctions for its actions. ➖Dust ➖To remove dust: I dusted the shelves yesterday. ➖To add a layer of fine particles: She dusted the cake with powdered sugar. ➖Overlook ➖To supervise or watch over: The manager will overlook the project. ➖To fail to notice something: I accidentally overlooked that mistake. ➖Clip ➖To attach or fasten: He clipped the papers together with a binder clip. ➖To cut or remove: The gardener clipped the hedges neatly. ➖Screen ➖To show or display something: The theater screened a new movie. ➖To block or shield: Trees screened the house from view. Can you think of any other words like that? Let me know in the comments 💬 Quiz Time! What do we call words that mean their own opposite? 🧐 A. Antonyms B. Palindromes C. Contronyms D. Capitonyms Tap ❤️ if you found this interesting @languagetrivia#theory#term

Hashtags

Language Trivia 🤔

@languagetrivia · Post #420 · 01.12.2024 г., 17:18

Sometimes, we don't want to be too direct with our words. For instance, instead of saying someone "died," we might say they "passed away." This way of softening our language helps us avoid discomfort or show sensitivity in delicate situations. People use this kind of phrasing in various scenarios: ➖To avoid offending someone (e.g. saying "full-figured" instead of "overweight") ➖To speak politely about jobs (e.g. "sanitation worker" instead of "garbage collector") ➖To make bad news sound less harsh (e.g. "let go" instead of "fired" or ”downsizing” instead of “cutting jobs”) ➖To talk about sensitive topics (e.g. "use the restroom" instead of "go to the toilet" or ”gosh" instead of "God") These phrases help us navigate social interactions tactfully, showing how language can soften or enhance our message. What do we call this practice of using less direct language to soften or sugarcoat an idea? Options: A) Oxymoron B) Metaphor C) Hyperbole D) Euphemism Take the quiz below to see the correct answer @languagetrivia#theory#term

Hashtags

Language Trivia 🤔

@languagetrivia · Post #361 · 21.11.2024 г., 13:39

❓What word hides behind the spoiler? Don't reveal it yet✋ "œ" and "æ" are examples of a ligature. A ligature occurs where two or more graphemes or letters are joined to form a single character. These were introduced in handwritten scripts and early printing to improve efficiency, aesthetics, and save space. In handwriting, they reduced the number of strokes needed to write certain letter combinations. In typesetting, they helped conserve space in narrow columns. For example, "œ" is used in French words like cœur (heart) and œuvre (work) and "æ" can sometimes be seen in English, as in encyclopædia. So what is it called when two or more letters are combined into a single character like "œ" and "æ"? A) Digraph B) Ligature C) Umlaut D) Diphthong Tap to reveal the correct answer: These characters are called ligatures Ligatures (Wikipedia) List of English words that may be spelled with a ligature And the other terms from above: ➖A digraph combines two letters for one sound (e.g., "sh") ➖An umlaut (¨) changes vowel sounds (e.g., regular "u" vs. "ü" as in über in German) ➖A diphthong blends two vowel sounds in one syllable (e.g., "ou" in house). Tap ❤️ if you've learnt something new. @languagetrivia#theory#term

Hashtags

Language Trivia 🤔

@languagetrivia · Post #299 · 09.11.2024 г., 16:29

What do you call it when a phrase or the components of a word get translated literally from one language to another and the original meaning is preserved? For instance, English "skyscraper" → French "gratte-ciel" (“scrape-sky”), German "Wolkenkratzer" (“cloud scraper”), Spanish "rascacielos" (“scrape skies”). Press ❤️ Follow @languagetrivia to learn more about languages #theory#term

Hashtags

Language Trivia 🤔

@languagetrivia · Post #274 · 04.11.2024 г., 15:00

There is a phenomenon where some twins develop a private “language” understood only by them, often using invented words, sounds, or gestures. It usually emerges in early childhood due to their close bond and shared environment and may fade as they learn standard language skills. What is the name of this phenomenon? Join 🦫@languagetrivia for more interesting language facts #theory#term

Hashtags

Language Trivia 🤔

@languagetrivia · Post #590 · 12.01.2025 г., 18:55

Did you know that the word apron has an interesting history? Originally, it was napron, derived from the Old French word naperon, meaning a small tablecloth or napkin. Over time, due to the way people spoke, the phrase “a napron” was misinterpreted as “an apron,” and the word changed! This linguistic shift happens when the boundaries between words are reinterpreted, often influenced by how words are pronounced. Another example is nickname, which came from "an eke name" (meaning an additional name) but was turned into "a nickname." What is this phenomenon, where words change due to a reinterpretation of their boundaries, called? A. Rebracketing B. Metathesis C. Semantic Change D. Semantic Broadening @languagetrivia#etymology#theory#term

Language Trivia 🤔

@languagetrivia · Post #447 · 07.12.2024 г., 18:36

With the help of what literary technique is the humorous effect in this meme achieved? Options: A) Spoonerism B) Pun C) In-joke D) Malapropism Take the quiz below to find out @languagetrivia#meme#term

Hashtags

Language Trivia 🤔

@languagetrivia · Post #367 · 22.11.2024 г., 12:17

The ampersand (&) symbol has a rich history intertwined with the evolution of the English alphabet. Originally, it was a ligature of the Latin word “et,” meaning “and.” Over time, this symbol became so integral to writing that it was included as the 27th character in the English alphabet, following ‘Z’. When reciting the alphabet, people would conclude with “X, Y, Z, and per se and,” which translates to “and, by itself, and.” This phrase was eventually slurred together into the single term “ampersand.” Source Tap ❤️ if you found this interesting @languagetrivia#theory#term#symbol#etymology