Заметка начинающим, которые часто сталкиваются с подобной непоняткой.
Ситуация следующая, есть список файлов:
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
🌎 The lost Etruscan language remains one of history’s great mysteries. Despite thousands of inscriptions, only parts have been decoded, as Etruscan is unrelated to Latin or Greek. Most surviving texts are funerary or religious, and the longest Etruscan text is on a linen mummy wrapping called the Liber Linteus. ✨
#history⚡#linguistics⚡#etruscan
👉subscribe Interesting Planet
🧩Which of these languages is agglutinative, meaning it builds words by adding simple parts that each express a meaning, rather than using separate words for each meaning?
Options:
Turkish
French
Chinese
English
Take the quiz below to find out
@languagetrivia#theory#linguistics#guess_the_languge
Құрметті Аударгазм клубының мүшелері!
Кейбір пікірлерге байланысты, "орысқұл, арабқұл, қытайқұл" деген ұлт пен болмысты балағайттайтын сөздерді, арна редакторы ретінде жақтырмайтымды ескертіп қоюдың орайы кеп тұр.
Мұнда тілдерді "ғылыми пән" (мүмкінінше) тұрғысында зерделеуге ұмтыламыз.
Тілі бөтен, түрі бөтенді бөлектеп, сабайтын құрал ретінде емес. Ұлтшыл патриот болсаңыз еш қарсылығымыз жоқ, бірақ арна бағыты бөлек, әрі ондай риториканы қолдамайтынымды ескеріп, арна мақсаты мен бағытына аздаған ізет танытуыңызды сұраймын.
Өз басым қазақ тілі ана тілім әрі басым тілім болған соң ғана мазмұн мен мәтінді көбіне қазақша жазамын.
Бұнымды әлдебір тілге қасақана басымдық беру емес, тарихи һәм кәсіби сәйкестік қана деп тапсаңыз игі еді.
Арнада үш тілдің кез келгеніне қатысты мәселені үш тілдің кез келгенінде тіл білімі тұрғысында бейтарап салыстырып, талқылауға болады.
Жаңа қосылған оқырманым, қош келдің, тұрақты оқырманым төзіміңе рақмет.
#тіл_білімі#языкознание#linguistics
Sindhu, Hindu, Indos, India — the modern name “India” ultimately traces back to the Sanskrit Sindhu, the great river named in the Rig‑Veda. As the name moved between languages it shifted: Iranian and some Indic neighbors changed initial s‑ to h‑ (Sindhu → Hindu), Arab and Persian speakers used related forms, and Greek writers rendered the people and land as Indos/India. Medieval European forms (Inde/Indie) circulated in manuscripts and maps, and by the 17th century the modern English name India returned via Latin, Spanish or Portuguese influence.
🌊📜🗺️
[Learn more]
@googlefactss
#etymology#history#linguistics#India#wordorigin
🎓 At the invitation of the Chair of Linguistics and Professional Communication in Foreign Languages at Ural Federal University (URFU), the Office of the Honorary Consul of South Africa in Yekaterinburg joined the graduation ceremony for this year’s linguists, translators, and language educators.
📚 As a token of appreciation, we presented the Chair with Jim Is Tired of Jo'burg by Mzuvukile Maqetuka, published last year by the URFU Publishing House and translated into Russian by Dr. Dmitry Pobedash, a faculty member of the Chair.
🤝 Also, we explored possible areas of cooperation for the upcoming academic year together with Dr. Maria Ilyushkina, Head of the Chair.
#URFU#Education#SouthAfrica#Translation#Linguistics#CulturalDialogue
The staff of the Honorary Consul's office gave a presentation on the Republic of South Africa and the role of Honorary Consul Sergey Mazurkevich to students in the Fundamental and Applied Linguistics and Roman-and-German Philology programs at the Department of Philology at Ural Federal University (URFU).
During the meeting, students had the opportunity to ask questions. After the presentation, we discussed potential avenues for further collaboration with Dr. Anna Plotnikova, Head of the Department.
#education#Yekaterinburg#URFU#Linguistics#Philology#SouthAfrica#HonoraryConsul#Mazurkevich
Snowclones are versatile phrase templates where key words can be swapped to create new, humorous meanings—like linguistic Mad Libs. Coined by linguists Geoffrey K. Pullum and Glen Whitman in 2004, they capture overused, customizable clichés popular in media and memes. Examples include “X is the new Y” or “I, for one, welcome our new X overlords.” They’re a fun way to remix language and culture. 🗣️🎭
Here’s a fresh snowclone to try out:
“X: Because sometimes, Y just isn’t enough.”
Examples:
- “Coffee: Because sometimes, sleep just isn’t enough.” ☕😴
- “Books: Because sometimes, reality just isn’t enough.” 📚✨
@googlefactss
#Snowclone#InternetCulture#Linguistics#Memes#LanguageFun