str هو تسلسل غير قابل للتغيير من نقاط ترميز Unicode.
وقد تشمل هذه النقاط حروفًا وعلامات تشكيل ومحارف تحديد الموضع وأرقامًا ورموز عملات وإيموجي وعلامات ترقيم ومسافات وفواصل أسطر، وغير ذلك.
تطبّق السلاسل النصية جميع عمليات التسلسل الشائعة، ويمكن المرور عليها باستخدام صيغة for item in <str> أو for index, item in enumerate(<str>).
يمكن الرجوع إلى نقاط الترميز المفردة (سلاسل نصية بطول 1) بفهرس 0-based index من اليسار، أو بفهرس -1-based index من اليمين.
يمكن دمج السلاسل النصية باستخدام <str> + <other str> أو <str>.join(<iterable>) وفصلها عبر <str>.split(<separator>).
كما تقدّم خيارات أخرى متعددة للتنسيق والتجميع.
وللتعمّق في العمل مع السلاسل النصية، يوفّر Python مجموعة غنية من طرق السلاسل النصية للبحث والتنظيف والتحويل والترجمة والعديد من العمليات الأخرى.
تشمل بعض طرق str الأكثر شيوعًا:
<str>.startswith(<substr>) و<str>.endswith(<substr>)
<str>.title() و<str>.upper()/<str>.lower() و<str>.swapcase()
<str>.strip(<chars>) أو <str>.lstrip(<chars>) أو <str>.rstrip(<chars>)
<str>.replace(<old>, <new>)
بما أن str غير قابل للتغيير، فإن قيمة كائن str في الذاكرة لا يمكن أن تتغيّر؛ والطرق التي تبدو وكأنها تعدّل سلسلة نصية إنما تُرجع نسخة جديدة أو كائن str جديدًا.
<str>.endswith(<suffix>) تُرجع True إذا انتهت السلسلة النصية بـ <suffix>، وFalse فيما عدا ذلك.
>>> 'My heart breaks. 💔'.endswith('💔')
True
>>> 'cheerfulness'.endswith('ness')
True
# Punctuation is part of the string, so needs to be included in any endswith match.
>>> 'Do you want to 💃?'.endswith('💃')
False
>>> 'The quick brown fox jumped over the lazy dog.'.endswith('dog')
False
<str>.title() تحلّل سلسلة نصية وتُكبّر أول «حرف» من كل «كلمة» تصادفها.
وفي Python، يعتمد ذلك بشكل كبير على ترميز اللغة المستخدم وعلى الطريقة التي تمثّل بها اللغة المعنية الكلمات والمحارف.
وقد توجد أيضًا قواعد إعدادات محلية مطبّقة على لغة أو مجموعة محارف معينة.
>>> man_in_hat_th = 'ผู้ชายใส่หมวก'
>>> man_in_hat_ru = 'мужчина в шляпе'
>>> man_in_hat_ko = '모자를 쓴 남자'
>>> man_in_hat_en = 'the man in the hat.'
>>> man_in_hat_th.title()
'ผู้ชายใส่หมวก'
>>> man_in_hat_ru.title()
'Мужчина В Шляпе'
>>> man_in_hat_ko.title()
'모자를 쓴 남자'
>> man_in_hat_en.title()
'The Man In The Hat.'
<str>.strip(<chars>) تُرجع نسخة من str بعد إزالة <chars> من البداية والنهاية.
نقاط الترميز المحدّدة في <chars> ليست بادئة ولا لاحقة، بل ستُزال كل التوليفات المكوّنة من نقاط الترميز هذه بدءًا من كلا طرفي السلسلة النصية.
وإذا لم يُحدَّد شيء في <chars>، فستُزال كل التوليفات المكوّنة من نقاط ترميز المسافات البيضاء.
وإذا أردت الإزالة من الجانب الأيسر فقط أو الجانب الأيمن فقط، يمكنك استخدام <str>.lstrip(<chars>) و<str>.rstrip(<chars>).
# This will remove "https://", because it can be formed from "/stph:".
>>> 'https://unicode.org/emoji/'.strip('/stph:')
'unicode.org/emoji'
# Removal of all whitespace from both ends of the str.
>>> ' 🐪🐪🐪🌟🐪🐪🐪 '.strip()
'🐪🐪🐪🌟🐪🐪🐪'
>>> justification = 'оправдание'
>>> justification.strip('еина')
'оправд'
# Prefix and suffix in one step.
>>> 'unaddressed'.strip('dnue')
'address'
>>> ' unaddressed '.strip('dnue ')
'address'
<str>.replace(<substring>, <replacement substring>) تُرجع نسخة من السلسلة النصية بعد استبدال كل حالات <substring> بـ <replacement substring>.
الاقتباس المستخدم أدناه مأخوذ من The Hunting of the Snark لـ Lewis Carroll
# The Hunting of the Snark, by Lewis Carroll
>>> quote = '''
"Just the place for a Snark!" the Bellman cried,
As he landed his crew with care;
Supporting each man on the top of the tide
By a finger entwined in his hair.
"Just the place for a Snark! I have said it twice:
That alone should encourage the crew.
Just the place for a Snark! I have said it thrice:
What I tell you three times is true."
'''
>>> quote.replace('Snark', '🐲')
...
'\n"Just the place for a 🐲!" the Bellman cried,\n As he landed his crew with care;\nSupporting each man on the top of the tide\n By a finger entwined in his hair.\n\n"Just the place for a 🐲! I have said it twice:\n That alone should encourage the crew.\nJust the place for a 🐲! I have said it thrice:\n What I tell you three times is true."\n'
>>> 'bookkeeper'.replace('kk', 'k k')
'book keeper'
🌟أُضيفت حديثًا في Python 3.9
يقدّم Python 3.9 طريقتين جديدتين للسلاسل النصية تجعلان إزالة البادئات واللواحق أسهل بكثير.
<str>.removeprefix(<substring>) تُرجع السلسلة النصية بدون البادئة (string[len(<substring>):]). وإذا لم تكن <substring> موجودة، فستحصل على نسخة من السلسلة النصية الأصلية.
# removing a prefix
>>> 'TestHook'.removeprefix('Test')
'Hook'
>>> 'bookkeeper'.removeprefix('book')
'keeper'
<str>.removesuffix(<substring>) تُرجع السلسلة النصية بدون اللاحقة (string[:-len(substring)]). وإذا لم تكن <substring> موجودة، فستحصل على نسخة من السلسلة النصية الأصلية.
# removing a suffix
>>> 'TestHook'.removesuffix('Hook')
'Test'
>>> 'bookkeeper'.removesuffix('keeper')
'book'
لمزيد من الأمثلة والطرق، يُعدّ الشرح التعليمي غير الرسمي نقطة انطلاق جيدة. ويقدّم كيفية التعامل مع Unicode في وثائق Python تفاصيل وافية حول Unicode والترميز والبايتات واعتبارات تقنية أخرى للتعامل مع السلاسل النصية في Python.
يدعم Python أيضًا التعبيرات النمطية عبر وحدة re، وسيُغطّى ذلك في مفهوم مستقبلي.