Метод строки split() разделяет строку на несколько строк по указанному символу
>>> "a_b_c".split('_')
['a', 'b', 'c']
Можно указать максимальное количество разделений
>>> "a_b_c".split('_', 1)
['a', 'b_c']
Или резать с другой стороны с помощью rsplit() (right split)
>>> "a_b_c".rsplit('_', 1)
['a_b', 'c']
А что будет если оставить аргументы пустыми?
>>> "a_b_c".split()
['a_b_c']
Получаем список с одним элементом, потому что по умолчанию используется пробельный символ.
>>> "a b c".split()
['a', 'b', 'c']
То есть это равнозначно такому вызову?
>>> "a b c".split(" ")
['a', 'b', 'c']
Кажется да, но нет! Давайте попробуем добавить пробелов между буквами
>>> "a b c".split(" ")
['a', '', '', 'b', '', '', 'c']
И вот картина уже не так предсказуема 😕
А вот что будет по умолчанию
>>> "a b c".split()
['a', 'b', 'c']
Всё снова красиво! 🤩
По умолчанию в качестве разделителя используется любой пробельный символ, будь то табуляция или новая строка. Включая несколько таких символов идущих подряд. А также игнорируются пробельные символы по краям строки.
>>> "a\t b\n c ".split()
['a', 'b', 'c']
Аналогичный способ можно собрать с помощью регулярного выражения. Но пробелы по краям строки придется обрабатывать дополнительно.
>>> import re
>>> re.split(r"\s+", ' a b c '.strip())
['a', 'b', 'c']
Здесь тоже можно указать количество разделений
>>> re.split(r"\s+", 'a b c', 1)
['a', 'b c']
А что если мы хотим написать красиво, то есть split() без аргументов, но при этом указать количество разделений? В этом случае первым аргументом передаём None
>>> "a\n b c".split(None, 1)
['a', 'b c']
Данный метод не учитывает строки с пробелами, взятые в кавычки
'a "b c" '.split()
['a', '"b', 'c"']
Но для таких случаев есть другие способы.
#tricks#basic
🇵🇭Des milliers de personnes bloquées à Quezon, aux #Philippines
Les grandes artères de la ville de Quezon ont été le théâtre de scènes de désespoir le 20 avril, alors que des milliers de usagers se sont retrouvés bloqués à cause d'une grève des transports provoquée par le coût élevé du carburant.
RT en français • Osez questionner !
🇵🇭Philippine Inflation Hits 3-Year High
Philippine annual inflation surged to 7.2% in April — the highest since March 2023 — as fuel prices spiked on the back of Middle East conflict, pushing costs across food, transport, and utilities. The figure exceeded the 5.5% economist consensus and broke through the central bank's own forecast ceiling of 6.4%.
The Bangko Sentral ng Pilipinas now faces pressure to act outside its regular meeting cycle. The April print signals that supply-side interventions are insufficient in the current external environment, raising the probability of an emergency rate hike to re-anchor expectations.
An off-cycle tightening move would mark a significant policy shift, complicating growth prospects as the Philippines absorbs both global commodity shocks and domestic demand pressures.
#Philippines
@asianomics
🇵🇭Mayon Volcano Pyroclastic Flow Triggers Mass Evacuation
Mayon volcano in Albay province triggered a mass evacuation of over 300 families after lava deposits on its southwestern slope collapsed into a pyroclastic flow on Saturday, blanketing 87 villages across three towns in dense ashfall. No explosive eruption occurred — the event stemmed from cascading hot rocks, ash, and gas. No deaths or injuries were reported.
Mayon has been in a state of mild, intermittent eruption since January. Philippine volcanology agency Phivolcs recorded 32 volcanic earthquakes over the weekend, including 25 tremors. Visibility dropped to zero on national roads, livestock were killed, and vegetable farms sustained damage across the affected towns.
Phivolcs confirmed the volcano had stabilized by Monday but maintained that underlying hazard conditions persist.
#Philippines
@asianomics
🇵🇭Mayon Volcano Erupts, Thousands Evacuated
Mayon Volcano in Albay province, south of Manila, erupted on May 2–3, prompting mass evacuations across surrounding communities. The Philippine volcanology institute raised Alert Level 3 out of five, reporting strombolian activity, lava fountaining, and risks of landslides and lava flows. A 6km radius danger zone has been enforced.
Nearly 1,500 families are sheltering in evacuation centres, according to the Department of Social Welfare and Development. Heavy ashfall blanketed multiple towns on May 2, disrupting traffic across the province. Mayon is one of the Philippines' most active volcanoes, with a documented history of recurring eruptive cycles.
Displacement is expected to expand if activity escalates beyond Alert Level 3.
#Philippines
@asianomics
🇵🇭#Philippines: Ten militants from the Dawlah Islamiya-Maute Group (DI-MG), which has sworn allegiance to ISIS, were killed in a one-hour-long firefight with Philippine government forces in Lanao del Sur earlier today. Of the 10 militants, 4 were reported to be female fighters.
As a result of the clash, four light weapons, a hand grenade, and several IED components were recovered.
🇵🇭Philippine Diesel Prices Break Triple-Digit Record
Diesel prices in the Philippines breached 100 pesos per litre for the first time on Tuesday, with the Department of Energy warning of prices as high as 114 pesos (US$1.90) per litre in Metro Manila. The surge follows weeks of consecutive increases driven by the war on Iran and its effect on global crude markets.
The spike exposed structural weaknesses in the Philippine energy sector. The chief economist at Union Bank of the Philippines noted that limited domestic refining capacity means local prices rapidly reflect movements in global crude and refined product markets.
Transport workers have been among the first to absorb the impact, with some reducing operating hours or leaving vehicles idle as fuel costs approach one-sixth of the minimum daily wage in the capital. The Department of Energy has flagged the risk of a domino effect on rice prices, electricity, and basic household goods.
#Philippines
@asianomics
🇵🇭#Philippines: CCTV footage shows an assassination attempt targeting the Mayor of Shariff Aguak in Maguindanao del Sur.
The attackers used an RPG and assault rifles during the attack. The attempt reportedly failed after the blast struck the mayor’s vehicle, which absorbed the impact. The gunmen were later killed in an exchange of fire with security forces.
(via @war_noir)
Сегодня, в третий день деловой миссии B2BASEAN, мы побывали на международной выставке продуктов питания, напитков и ингредиентов IFEX Philippines. 🇵🇭
Мы познакомились с местным экспонентом, предоставили консультации и поделились опытом работы на российском продовольственном рынке.
Мы встретились с нашим партнером-поставщиком филиппинских бананов и обсудили возможность возобновления поставок в Россию бананов премиум класса с Филиппин.
#Philippines
Сегодня мы продолжили нашу деловую миссию на Филиппинах, посетив офис Национальной Корпорации Развития (NDC), ведущего государственного предприятия Филиппин, которое инвестирует в различные отрасли промышленности на Филиппинах.
Встреча была организована B2BASEAN совместно с Торгпредством России на Филиппинах. Обсуждались возможности сотрудничества в области инновационных проектов и организации цифрового хаба на Филиппинах
#PHILIPPINES
Philippines🌴
Isla de Gigantes, in the Great Western Visayas, is a paradise home to many protected species, including rare mammals, birds, and reptiles like frigatebirds and softshell turtles. 🐢🦜
#Philippines | @voyage
🏝 Makapuya Island — a tropical fairy tale of the Philippines 🌊✨
✨ An abandoned paradise at the edge of the world Makapuya is one of those islands where you feel like the star of a movie about a secluded getaway. White sand, coconut palms, and turquoise waters 🥥💦
#Philippines | @voyage
🏝 Makapuya Island — a tropical fairy tale of the Philippines 🌊
✨
✨ An abandoned paradise at the edge of the world Makapuya is one of those islands where you feel like the star of a movie about a secluded getaway. White sand, coconut palms, and turquoise waters 🥥💦
#Philippines | @voyage