0Pricing
Pandas & NumPy Academy · درس

موصّل .str

يمكنك الوصول إلى أساليب السلاسل النصية في Series باستخدام .str، وتطبيق lower() وupper() وstrip() وlen() على جميع القيم.

موصّل .str درس مجاني في Pandas & NumPy Academy على CoddyKit. هذا هو الدرس 1 من أصل 4. يمكنك قراءة الدرس كاملاً أدناه مجاناً — ثم تمرن عليه مباشرة في المتصفح باستخدام محرر أكواد مدمج ومدرس ذكاء اصطناعي متاح 24/7. هذا الدرس جزء من مسار التعلم في Pandas & NumPy Academy، وتقدمك يتزامن عبر الويب وتطبيق CoddyKit. تتضمن دورة Pandas & NumPy Academy 4 دروس في المجموع.

بعض أجزاء هذا الدرس لم تُترجم بعد وتظهر باللغة الإنجليزية.

Introduction to the .str Accessor

Python strings have many useful methods like .lower(), .strip(), and .replace(), but you cannot call them directly on a Pandas Series of strings — you would need a loop. The .str accessor solves this by exposing vectorised versions of Python's built-in string methods on a Series, applying the operation to every element at once without writing a loop and handling NaN gracefully (it returns NaN for missing values).

import pandas as pd

names = pd.Series(['  Alice ', 'BOB', '  carol  '])

# .strip() removes leading/trailing whitespace from every element
print(names.str.strip())
# 0    Alice
# 1      BOB
# 2    carol

# .lower() lowercases every element
print(names.str.strip().str.lower())
# 0    alice
# 1      bob
# 2    carol

Case Conversion Methods

Inconsistent capitalisation is one of the most common data quality issues. The .str accessor provides .lower(), .upper(), .title() (first letter of each word capitalised), and .capitalize() (only first letter of the string). Use .lower() before comparisons and groupby operations to avoid treating 'NYC' and 'nyc' as different groups.

import pandas as pd

df = pd.DataFrame({'city': ['new york', 'LOS ANGELES', 'Chicago', 'HOUSTON']})

df['city_lower'] = df['city'].str.lower()
df['city_title'] = df['city'].str.title()
df['city_upper'] = df['city'].str.upper()

print(df[['city_lower', 'city_title']])
#    city_lower   city_title
# 0   new york     New York
# 1  los angeles  Los Angeles
# 2    chicago      Chicago
# 3    houston      Houston

Stripping Whitespace

Leading and trailing whitespace is invisible in displays but causes exact-match comparisons to silently fail. .str.strip() removes whitespace from both ends, .str.lstrip() removes from the left only, and .str.rstrip() removes from the right only. You can also pass a specific character to strip (e.g., .str.strip('$') removes dollar signs).

import pandas as pd

df = pd.DataFrame({'code': ['  A001  ', '$B002$', '  C003']})

print(df['code'].str.strip())     # 'A001', '$B002$', 'C003'
print(df['code'].str.strip('$ ')) # 'A001', 'B002', 'C003'

Checking Length with .str.len()

.str.len() returns the number of characters in each string element as an integer Series. This is useful for validation — checking that a product code is always 5 characters, that a phone number has the right digit count, or that a text field is not suspiciously short (e.g., a single character suggesting a placeholder).

import pandas as pd

df = pd.DataFrame({'sku': ['A001', 'BB02', 'CCC', 'D0005', 'E1']})

df['sku_len'] = df['sku'].str.len()
print(df)

# Rows with unexpected SKU length
bad_skus = df[df['sku_len'] != 4]
print(bad_skus)
#     sku  sku_len
# 2   CCC        3
# 3  D0005        5
# 4    E1        2

Checking Prefixes and Suffixes

.str.startswith() and .str.endswith() return boolean Series. These are the cleanest way to filter rows based on how a string value begins or ends — for example, selecting all order IDs that start with 'ORD' or all file names that end with '.csv'. They also accept tuples of strings to check multiple prefixes/suffixes at once.

import pandas as pd

df = pd.DataFrame({'file': ['data.csv', 'report.xlsx', 'backup.csv', 'config.json']})

# Filter CSV files
csv_files = df[df['file'].str.endswith('.csv')]
print(csv_files)
#         file
# 0   data.csv
# 2  backup.csv

# Multiple suffixes
spreadsheets = df[df['file'].str.endswith(('.csv', '.xlsx'))]
print(spreadsheets.shape)  # (3, 1)

.str.contains() for Substring Search

.str.contains(pattern) returns a boolean Series indicating whether each element contains the given pattern. By default it accepts a regular expression, but you can pass regex=False for a literal substring search. The na=False argument treats NaN as not matching instead of propagating NaN to the result.

import pandas as pd

df = pd.DataFrame({
    'description': ['Red apple', 'Green banana', 'Red cherry', None, 'Blue grape']
})

# Find rows containing 'Red' (case-sensitive)
mask = df['description'].str.contains('Red', na=False)
print(df[mask])
#    description
# 0   Red apple
# 2  Red cherry

NaN Behaviour in .str Methods

When a Series contains NaN values, most .str methods propagate NaN by default — they return NaN for the missing positions in the output Series. Methods that return boolean values (like .str.contains()) default to returning NaN for missing positions, which can cause issues with boolean indexing. Use na=False to treat NaN as non-matching, or na=True to treat it as matching.

import pandas as pd
import numpy as np

s = pd.Series(['hello', None, 'world', np.nan])

# Default: NaN propagates
print(s.str.upper())
# 0    HELLO
# 1     None
# 2    WORLD
# 3      NaN

# contains with na=False: NaN treated as non-matching
print(s.str.contains('o', na=False))
# 0     True
# 1    False
# 2     True
# 3    False

.str.count() for Pattern Frequency

.str.count(pattern) counts the number of times a pattern appears in each string element. This is useful for feature engineering in natural language processing — for example, counting how many times a word appears, how many digits a string contains, or how many commas separate values in a delimited field.

import pandas as pd

df = pd.DataFrame({'text': ['hello world', 'foo bar baz', 'a b c d e']})

# Count number of words (spaces + 1)
df['word_count'] = df['text'].str.count(' ') + 1
print(df)
#           text  word_count
# 0  hello world           2
# 1  foo bar baz           3
# 2    a b c d e           5

Chaining .str Methods

Because each .str method returns a new Series, you can chain multiple string operations in one expression. This is the cleanest way to apply several cleaning steps to a text column: strip whitespace, lowercase, and remove special characters — all in a single readable line. The chain evaluates left to right, with each step feeding into the next.

import pandas as pd

df = pd.DataFrame({'tag': ['  Python  ', ' DATA-SCIENCE ', ' Machine_Learning !']})

df['tag_clean'] = (
    df['tag']
    .str.strip()
    .str.lower()
    .str.replace('[-_!]', ' ', regex=True)
    .str.strip()
)
print(df)
#                      tag           tag_clean
# 0            Python       python
# 1       DATA-SCIENCE     data science
# 2  Machine_Learning !  machine learning

Indexing Characters with .str[]

The .str[n] notation extracts the character at position n from each string, and .str[start:end] extracts a substring slice. This is vectorised indexing into the strings, useful for extracting fixed-width codes like postal code prefixes, year digits from date strings, or the first letter of a name.

import pandas as pd

df = pd.DataFrame({'code': ['NYC-001', 'LAX-042', 'ORD-018']})

# Extract city code (first 3 chars)
df['city'] = df['code'].str[:3]

# Extract numeric part (chars 4 onwards)
df['num'] = df['code'].str[4:]

print(df)
#       code city num
# 0  NYC-001  NYC 001
# 1  LAX-042  LAX 042
# 2  ORD-018  ORD 018

Practical Cleaning with .str

Here is a realistic text cleaning pipeline for a product name column that was scraped from a web page. It combines stripping, case normalisation, punctuation removal, and whitespace collapse — a standard pre-processing sequence in any NLP or data cleaning task.

import pandas as pd

df = pd.DataFrame({
    'product': ['  Apple iPhone 15!!', 'samsung GALAXY s24 ', '  Google Pixel 8  Pro  ']
})

df['product_clean'] = (
    df['product']
    .str.strip()
    .str.title()
    .str.replace('[^A-Za-z0-9 ]', '', regex=True)  # remove punctuation
    .str.replace(r'\s+', ' ', regex=True)            # collapse extra spaces
    .str.strip()
)
print(df['product_clean'].tolist())
# ['Apple Iphone 15', 'Samsung Galaxy S24', 'Google Pixel 8 Pro']

Quick Check

Test your understanding of the .str accessor.

Lesson Recap

In this lesson you learned: the .str accessor exposes vectorised string methods on a Pandas Series, including lower/upper/strip for normalisation, startswith/endswith/contains for filtering, and len/count for measurement. Chain multiple .str calls to build readable cleaning pipelines. Use na=False when NaN values are present. Next up we split and replace strings for more advanced transformations.

الأسئلة الشائعة

هل درس «موصّل .str» مجاني؟

نعم — نص درس «موصّل .str» كامل متاح مجاناً هنا على الويب. لتمرينه بشكل تفاعلي (محرر أكواد مدمج ومدرس ذكاء اصطناعي متاح 24/7) وفتح باقي دورة Pandas & NumPy Academy، انتقل إلى CoddyKit PRO. تتضمن دورة Pandas & NumPy Academy 4 دروس في المجموع.

ماذا ستتعلم في «موصّل .str»؟

يمكنك الوصول إلى أساليب السلاسل النصية في Series باستخدام .str، وتطبيق lower() وupper() وstrip() وlen() على جميع القيم. تتمرن على Pandas & NumPy Academy مع أكواد عملية تشغلها مباشرة في المتصفح، ومدرس ذكاء اصطناعي متاح 24/7 يجيب على أسئلتك أثناء عملك.

هل أحتاج إلى خبرة سابقة لأبدأ Pandas & NumPy Academy؟

لا تُشترط خبرة سابقة. Pandas & NumPy Academy على CoddyKit منظم للمبتدئين حتى المتقدمين، لذا يمكنك البدء من هنا أو من البداية والتقدم بسرعتك الخاصة. هذا هو الدرس 1 من أصل 4.

كم من الوقت يستغرق درس «موصّل .str»؟

معظم دروس CoddyKit تستغرق حوالي 5–10 دقائق. كل منها موجز وتفاعلي، لذا تحرز تقدماً مستمراً وتستأنف من حيث توقفت عبر الويب والتطبيق.

هل يمكنني كتابة وتشغيل أكواد في درس Pandas & NumPy Academy هذا؟

نعم. كل درس في Pandas & NumPy Academy يتضمن محرر أكواد مدمج، لذا تكتب وتشغل أكواداً حقيقية مباشرة في متصفحك وتحصل على تعليقات فورية من الذكاء الاصطناعي — بدون إعداد محلي.

جميع الدروس في هذه الدورة

  1. موصّل .str
  2. تقسيم السلاسل النصية واستبدالها
  3. مطابقة الأنماط باستخدام Regex
  4. دمج أعمدة النص وتنظيفها
← العودة إلى Pandas & NumPy Academy