🌐 Detecting your location…
📢 Advertisement — Configure AdSense in Appearance → Customize → AdSense Settings

الدليل الكامل لأساليب سلسلة بايثون 2026: جميع الطرق مع الأمثلة

⏱️3 min read  ·  520 words

تعد أساليب سلسلة بايثون من بين الأدوات الأكثر استخدامًا في مجموعة أدوات أي مطور بايثون. في عام 2026، يعد إتقان معالجة السلسلة أمرًا ضروريًا لاستخراج الويب وتنظيف البيانات وعمل واجهة برمجة التطبيقات ومعالجة النصوص. يغطي هذا الدليل الكامل كل طريقة سلسلة مهمة مع أمثلة عملية.

طرق السلسلة الأساسية

# String creation and basic info
text = "  Hello, Python World!  "
print(len(text))          # 24 (including spaces)
print(type(text))         # <class 'str'>

# Case transformation
print(text.upper())       # "  HELLO, PYTHON WORLD!  "
print(text.lower())       # "  hello, python world!  "
print(text.title())       # "  Hello, Python World!  "
print(text.capitalize())  # "  hello, python world!  " (only first char)
print(text.swapcase())    # "  hELLO, pYTHON wORLD!  "

# Whitespace removal
print(text.strip())       # "Hello, Python World!" (both sides)
print(text.lstrip())      # "Hello, Python World!  " (left only)
print(text.rstrip())      # "  Hello, Python World!" (right only)
print(text.strip("!. ")) # removes those chars from both ends

طرق البحث والاختبار

s = "Hello, Python World!"

# Finding substrings
print(s.find("Python"))      # 7 (returns -1 if not found)
print(s.index("Python"))     # 7 (raises ValueError if not found)
print(s.rfind("l"))          # 14 (search from right)
print(s.count("l"))          # 3

# Boolean checks
print(s.startswith("Hello"))  # True
print(s.endswith("!"))        # True
print(s.startswith(("Hi", "Hello")))  # True (tuple of prefixes)

# Content checks
print("abc123".isalnum())    # True (only alphanumeric)
print("Hello".isalpha())     # True (only letters)
print("12345".isdigit())     # True (only digits)
print("   ".isspace())       # True (only whitespace)
print("HELLO".isupper())     # True
print("hello".islower())     # True
print("Python 3.12".isprintable())  # True

طرق التعديل

# Replace
s = "Hello World Hello"
print(s.replace("Hello", "Hi"))          # "Hi World Hi"
print(s.replace("Hello", "Hi", 1))       # "Hi World Hello" (max 1 replacement)

# Split and join
csv = "Alice,Bob,Carol,Dave"
print(csv.split(","))         # ["Alice", "Bob", "Carol", "Dave"]
print(csv.split(",", 2))      # ["Alice", "Bob", "Carol,Dave"] (max 2 splits)

lines = "line1
line2
line3"
print(lines.splitlines())    # ["line1", "line2", "line3"]

# Join — build string from list
words = ["Python", "is", "awesome"]
print(" ".join(words))       # "Python is awesome"
print("-".join(words))       # "Python-is-awesome"
print("".join(["a","b","c"])) # "abc"

# Padding and alignment
print("hello".center(11, "*"))  # "***hello***"
print("hi".ljust(10, "."))      # "hi........"
print("hi".rjust(10, "."))      # "........hi"
print("42".zfill(5))            # "00042" (zero-fill for numbers)

طرق التنسيق والقالب

# f-strings (best, Python 3.6+)
name = "Alice"
age = 30
print(f"Name: {name}, Age: {age}")
print(f"Pi: {3.14159:.2f}")        # Pi: 3.14
print(f"Hex: {255:#010x}")         # Hex: 0x000000ff
print(f"1000000: {1_000_000:,}")   # 1000000: 1,000,000

# format() method
print("Hello, {}!".format(name))
print("{0} + {1} = {2}".format(2, 3, 2+3))
print("{name} is {age}".format(name="Bob", age=25))

# Template strings (safe for user input)
from string import Template
t = Template("Hello, $name!")
print(t.substitute(name="Alice"))    # "Hello, Alice!"
print(t.safe_substitute())           # "Hello, $name!" (no KeyError)

# encode/decode
s = "Hello, 世界"
encoded = s.encode("utf-8")   # bytes
decoded = encoded.decode("utf-8")  # string back

معالجة سلسلة العالم الحقيقي

# Clean user input
def clean_username(raw: str) -> str:
    return raw.strip().lower().replace(" ", "_")[:30]

# Parse CSV line
def parse_csv_line(line: str) -> list[str]:
    return [field.strip().strip('"') for field in line.split(",")]

# Validate email (simple)
def is_valid_email(email: str) -> bool:
    email = email.strip().lower()
    return "@" in email and "." in email.split("@")[1]

# Extract numbers from string
import re
text = "I have 3 cats and 12 dogs"
numbers = [int(n) for n in re.findall(r'\d+', text)]  # [3, 12]

# Camel to snake case
def camel_to_snake(name: str) -> str:
    s = re.sub(r'([A-Z]+)([A-Z][a-z])', r'_', name)
    return re.sub(r'([a-z\d])([A-Z])', r'_', s).lower()

# Truncate with ellipsis
def truncate(text: str, max_len: int = 100) -> str:
    return text[:max_len-3] + "..." if len(text) > max_len else text

تعد أساليب سلسلة بايثون أساس معالجة النصوص. الشريط الرئيسي/التقسيم/الانضمام لتنظيف البيانات، والبحث/الاستبدال لتحويل النص، وتنسيق السلاسل للإخراج. يغطي الجمع بين الخيوط f (الحديثة) والتقسيم/الربط 90% من أعمال السلسلة اليومية.

✍️ Leave a Comment

Your email address will not be published. Required fields are marked *

🌐 Read in:🇬🇧 English🇩🇪 Deutsch🇧🇷 Português🇸🇦 العربية🇮🇳 हिन्दी