Python String Length and Indexing Guide | len() & Indexes
Master Python strings with this guide on the len() function, zero-based indexing, negative indexes, and avoiding common IndexError exceptions.
הפונקציה len() בפייתון
פונקציה מובנית המחזירה את אורך המחרוזת (מספר התווים).
len(string)
סופרת את כל סוגי התווים: אותיות, מספרים וסימנים.
שימוש נפוץ: לולאות, בדיקות תקינות קלט וחיתוך מחרוזות.
רווח הוא תו לכל דבר ונחשב בספירה!
word = <span style="color: #CE9178;">"Hello"</span>\n<span style="color: #569CD6;">print</span>(<span style="color: #DCDCAA;">len</span>(word)) <span style="color: #6A9955;"># 5</span>
נקודות חשובות על len()
len() סופרת כמה תווים יש.
היא לא נותנת מיקום (אינדקס).
האינדקסים מתחילים מ־0.
word = <span style="color: #CE9178;">"Python"</span> <span style="color: #569CD6;">print</span>(<span style="color: #DCDCAA;">len</span>(word)) <span style="color: #6A9955;"># 6</span>
נוסחה חשובה:
index_last = len(word) - 1
Indexes in Python
An index is the position of a character in a string. It allows you to access specific parts of text data.
Warning: Indexes start at 0
# P
# t
Negative Indexes
Python allows negative indexes. They count from the end of the string.
n
o
Using len() With Indexes
The connection between length and the last index
word = "Python"
len(word) # Returns 6
The last index is always <strong>len(word) - 1</strong>.
Common Error: IndexError
What happens when you access an index that doesn't exist?
Strings are zero-indexed. <strong style="color: #4CAF50;">'H'</strong> is at index 0 and <strong style="color: #4CAF50;">'i'</strong> is at index 1. Trying to access index <strong style="color: #FF5252;">2</strong> causes an error because it's out of bounds.
string index out of range
מהו אינדקס?
אינדקס הוא המיקום של תו במחרוזת.
שימו לב: האינדקס הראשון הוא 0
P
y
t
h
o
n
0
1
2
3
4
5
אינדקסים שליליים
אינדקס שלילי מתחיל מהסוף ומאפשר גישה נוחה לאיברים האחרונים.
1- הוא התו האחרון, 2- הוא התו הלפני אחרון, וכן הלאה. השיטה חוסכת חישוב אורך הרשימה ידנית.
word = "Python" print(word[-1]) # Output: n
הקשר בין len() לאינדקסים
האינדקס האחרון הוא:
שגיאה נפוצה
נקבל שגיאה כי אין אינדקס 2 ברשימה או במחרוזת.
- python
- string-methods
- coding-basics
- programming-tutorial
- len-function
- indexerror