Скорее всего уже слышали, что складывать строки через + это плохая практика. Падение производительности, и всё такое. Без лишних слов, давайте измерять:
from timeit import timeit
def t1():
# складываем 10 строк через + из переменной
t = 'text'
for _ in range(1000):
s = t + t + t + t + t + t + t + t + t
def t2():
# склеиваем список строк через метод join
arr = ['text'] * 10
for _ in range(1000):
s = ''.join(arr)
def t3():
# складываем через + но не из переменной а непосредственно инлайн объекты
for _ in range(1000):
s = 'text' + 'text' + 'text' + ... # всего 10 раз
Теперь каждую строку склейки запустим по 10М раз
>>> timeit(t1, number=10000)
0.21951690399964718
>>> timeit(t2, number=10000)
1.4978306379998685
>>> timeit(t3, number=10000)
0.2213820789993406
Хм, а нам говорили что через "+" это плохо и медленно ))) 😁
Тут стоит учитывать, что речь идёт о склейке множества длинных строк.
Давайте изменим условия:
def t4():
t = 'text'*100
for _ in range(1000):
s = t + t + t + t + t + t + t + t + t
def t5():
arr = ['text'*100] * 10
for _ in range(1000):
s = ''.join(arr)
def t6():
for _ in range(1000):
s = 'text'*100 + 'text'*100 + ... # всего 10 раз
>>> timeit(t4, number=10000)
12.795130728000004
>>> timeit(t5, number=10000)
2.642637542999182
>>> timeit(t6, number=10000)
0.2184546610005782
Вот, уже другой разговор, сразу видна разница, в среднем в 6 раз. Но погодите, почему последний тест t6() по скорости такой же как и t3()? Ведь строки теперь в 100 раз длиннее!
Это вопросы оптимизации кода, какие простые изменения ускоряют или замедляют выполнение программы. Мы столкнулись с примером обхода обращения к переменной. Например, именно так работает директива #define в С++, во время компиляции подставляя значение переменной вместо ссылки на неё.
В Python это тоже работает, но часто ли вы сможете встретить такой способ работы со строками? К сожалению, способ почти только теоретический.
В целом, тесты показали то, что мы хотели. Делаем выводы самостоятельно.
Полный листинг 🌍
#tricks
🇹🇩#Chad: Chadian security forces carried out a large-scale sweep yesterday in N’Djamena, seizing a significant cache of weapons and military equipment allegedly destined for militant groups.
Authorities recovered dozens of firearms, over 1,000 rounds of ammunition, military gear, and vehicles during coordinated raids across multiple districts. Several suspects were arrested. Among the stash of weaponry, a bow with arrows was also seized.
(via @ZagazOlaMakama on X & tribuneechos.com)
#Chad relocates #Sudan refugees as army deploys near border
Chad has begun the emergency relocation of refugees from its border with Sudan as the army prepares to deploy to the area in response to cross-border attacks, an official from the country's refugee agency told Reuters on Monday.
President Mahamat Idriss Deby last week ordered the army to prepare to retaliate after a cross-border drone attack from Sudan killed 17 people in Chad including mourners attending a funeral service.
A separate government statement last week said Chad had strengthened its security presence at the border and could potentially carry out operations on Sudanese territory.
Initial refugee relocation operations will involve around 2,300 people, more than half of them women and children, said Saleh Tebir Souleymane, the representative in the border town of Tine for Chad's National Commission for the Reception and........
https://www.reuters.com/world/africa/chad-relocates-sudan-refugees-army-deploys-near-border-2026-03-23/
🇹🇩#Chad - 🇸🇩#Sudan: Clashes have broken out between the Chadian military and Rapid Support Forces (RSF) after RSF militants attacked an outpost in Tissi near the Chad - Sudan border.
Earlier yesterday, 10 people were killed and 29 injured in two drone attacks in the Tina area near the Sudan - Chad border, reportedly carried out by a suspected RSF drone. The footage was recorded by a Chadian soldier.
(📹 via @BlazianP on X)
🇸🇩#Sudan - 🇹🇩#Chad: A Sudanese Armed Forces (SAF) Akinci drone carried out multiple strikes on the Adré border crossing between Sudan and Chad yesterday, causing large explosions after destroying several trucks.
The crossing has been a critical supply route for military equipment headed to Rapid Support Forces (RSF) inside Sudan.
(via @AfriMEOSINT on X)
#Chadian president orders "complete closure" of border with #Sudan after deadly drone attack
Chadian President Mahamat Idriss Deby Itno convened an emergency security meeting on Wednesday evening following a deadly drone attack along the #Chad-#Sudan border and ordered the "complete closure" of the border, according to a statement issued by the Chadian presidency.
The attack on Wednesday caused "several Chadian casualties," according to the statement. Local media reported that 16 people were killed.
The president instructed Prime Minister Allamaye Halina to dispatch a government delegation to the site to assess both human and material damage, the statement said.
He also ordered the National Army to retaliate against any attack originating from Sudan, it added, according to report by Xinhua
In related news the latest heavy fighting between warring parties along Sudan’s border with ....
https://www.facebook.com/AddisstandardEng/posts/pfbid0r5RXzFSFKQR4zeSqWPvSbrpjyViPKFYXPsFzHR2PDazB53J8fBbbJQyoMXiGAp6Dl
🎉🇹🇩В Чаде открылся Международный фестиваль культур народов Сахары
В Чаде прошла официальная церемония открытия шестого Международного фестиваля культур народов Сахары (FICSA). Фестиваль посетила делегация правительства Буркина-Фасо во главе с премьером Римтальбой Жаном Эммануэлем Уэдраого, премьер-министры Нигера Али Махаман Ламин Зейн и Чада Алла-Май Халина.
🗣️Как отметили в пресс-службе, фестиваль посвящен продвижению культурного разнообразия, туризма и диалога между народами региона.
«Премьер-министр Чада подчеркнул, что фестиваль выходит за рамки обычного культурного праздника и способствует развитию территорий Сахары как центров культуры, туризма и экономических возможностей, превращая Сахару в живое наследие, несущее смысл, ценность и будущее», – сообщается в пресс-релизе.
🇧🇫Также к участникам мероприятия обратился министр связи, культуры, искусства и туризма Буркина-Фасо Пингвенде Жилььбер Уэдраого, отметивший прочность исторических связей между между Уагадугу и Нджаменой. Он передал властям Чада приветствия от лидера Буркина-Фасо Ибрагима Траоре, а также заявил, что культура в Сахаро-Сахельском регионе является «рычагом социальной сплоченности» на фоне угроз безопасности.
На фестивале выступят коллективы из Нигера, Буркина-Фасо, Марокко, Мавритании и Чада, с целью продемонстрировать богатство культурного наследия народов Сахары и создать площадку для укрепления региональной интеграции.
#Новости_МеждународкаФМ
#AfricaNewsWithIYF
👉Read in ENG
👉Читайте нас в ВК
#Africa#Африка#Chad#Чад
News: #UK sanctions six individuals over #Sudan war atrocities, mercenary recruitment
Mekelle - #Britain has imposed sanctions on six individuals accused of committing atrocities during Sudan’s ongoing war or of fueling the conflict through the recruitment of mercenaries and the supply of military equipment, the UK government announced on Thursday.
According to the statement, those targeted include senior commanders from both the Sudanese Armed Forces (#SAF) and the paramilitary Rapid Support Forces (#RSF), as fighting between the two rivals continues to devastate the country.
British Foreign Secretary Yvette Cooper, who recently visited the Sudan–#Chad border, stressed the urgency of ending the conflict. “We urgently need a ceasefire, and safe access for humanitarian relief agencies to reach all those in need,” she said.
“Through these sanctions, we will seek to dismantle the.....
https://web.facebook.com/AddisstandardEng/posts/pfbid0TshoqtpBaQELM9k7VLoTH94aNHWprwMNiKo1kCSfMsTt9gutZ8rGmvmCZcNZ5kjrl
Africa Cup of Nations - Qualification🌍
2026-03-27 13:00 UTC
Somalia vs. Mauritius
Predicted outcome: Mauritius❌
Predicted score: 0:1
Actual: Draw 0:0
#Somalia#Mauritius
2026-03-27 13:00 UTC
Chad vs. Burundi
Predicted outcome: Draw❌
Predicted score: 1:1
Actual: Burundi 0:4
#Chad#Burundi
2026-03-27 16:00 UTC
Sao Tome and Principe vs. Ethiopia
Predicted outcome: Ethiopia✅
Predicted score: 1:2
Actual: Ethiopia 0:3
#SaoTomeandPrincipe#Ethiopia
#Football#AfricaCupofNations
News: #UN warns escalating hostilities along #Sudan’s borders, including with #Ethiopia, threaten civilians and disrupt aid operations
Escalating hostilities along Sudan’s borders, including with Ethiopia, are endangering civilians and disrupting humanitarian operations, the United Nations has warned.
According to a report by Xinhua, citing the UN Office for the Coordination of Humanitarian Affairs (#OCHA), recent clashes near Sudan’s frontiers with Ethiopia and #Chad have resulted in civilian casualties and forced displacement.
In #Blue_Nile State, violence near the Ethiopian border has restricted access to key regions including #Kurmuk, #Sali, and #Dindraw, south of the state capital, #Ed_Damazine. Civilians have reportedly fled toward Ed Damazine and across the border into Ethiopia in search of safety.
Sudanese officials have accused Ethiopia of facilitating operations by the paramilitary Rapid Support Forces (#RSF) and allied groups—an allegation.......
Read more: https://addisstandard.com/?p=56160