معالجة النصوص المتقدمة
1. تقسيم النصوص (.split())
تقوم دالة .split() بتقسيم النص إلى قائمة من النصوص الفرعية بناءً على فاصل محدد. إذا لم يتم تحديد فاصل، فإنها تقسم بناءً على المسافات.
python data = 'Apple,Banana,Cherry,Date'
التقسيم باستخدام الفاصلة
fruits = data.split(',') print(fruits) # المخرجات: ['Apple', 'Banana', 'Cherry', 'Date']
sentence = 'Python is fun to learn' words = sentence.split() print(words) # المخرجات: ['Python', 'is', 'fun', 'to', 'learn']
2. دمج النصوص (.join())
دالة .join() هي عكس split(). فهي تقوم بدمج قائمة من النصوص باستخدام نص معين ليكون الفاصل بينها.
python words_list = ['Welcome', 'to', 'the', 'course']
الدمج باستخدام مسافة
result_space = ' '.join(words_list) print(result_space) # المخرجات: Welcome to the course
الدمج باستخدام شرطة سفلية
result_underscore = '_'.join(words_list) print(result_underscore) # المخرجات: Welcome_to_the_course
3. استبدال النصوص الفرعية (.replace())
تستبدل كل تكرارات نص فرعي محدد بنص آخر.
python message = 'The cat sat on the mat. Cat is sleepy.' new_message = message.replace('Cat', 'Dog') print(new_message) # المخرجات: The Dog sat on the mat. Dog is sleepy.
يمكنك تحديد عدد المرات المسموح باستبدالها
limited_replace = message.replace('the', 'a', 1) print(limited_replace) # المخرجات: The cat sat on a mat. Cat is sleepy.