מחרוזותStrings
אינדקסים, חיתוך, מתודות של מחרוזות ועיצוב פלט.
Indexing, slicing, string methods and formatting output.
01אינדקסים ו-lenIndexing and len
מחרוזת היא רצף של תווים. לכל תו יש אינדקס, והספירה מתחילה ב-0. אינדקס שלילי סופר מהסוף: -1 הוא התו האחרון. len מחזירה כמה תווים יש.
A string is a sequence of characters. Each has an index, and counting starts at 0. A negative index counts from the end: -1 is the last character. len returns how many characters there are.
word = "Python"
print(word[0], word[1], word[-1])
print(len(word))
print(word[len(word) - 1])P y n 6 n
צפו בהרצה צעד אחר צעדWatch it run, step by step
מה קורה עכשיוWhat happens now
הקופסאות (משתנים)The boxes (variables)
מסך הפלטOutput screen
אינדקס הוא כמו מספר מושב בשורה בקולנוע, רק שהמושב הראשון הוא 0. ומי שיושב אחרון תמיד מקבל גם את המספר -1.
An index is like a seat number in a cinema row, except the first seat is 0. Whoever sits last also always gets the number -1.
פונים לאינדקס שלא קיים. ב-"Python" יש 6 תווים, אז האינדקס האחרון הוא 5.
Asking for an index that doesn't exist. "Python" has 6 characters, so the last index is 5.
word = "Python"
print(word[6])Traceback (most recent call last):
File "/Users/you/python-course/index.py", line 2, in <module>
print(word[6])
~~~~^^^
IndexError: string index out of rangeIndexError: string index out of range: האינדקס הגבוה ביותר הוא len(word) - 1.IndexError: string index out of range: the highest index is len(word) - 1.צפו איפה זה נשברWatch where it breaks
מה קורה עכשיוWhat happens now
הקופסאות (משתנים)The boxes (variables)
מסך הפלטOutput screen
02חיתוך מחרוזותSlicing
חיתוך לוקח חתיכה מהמחרוזת: s[start:stop]. ה-start נכלל, ה-stop לא. אפשר להשמיט התחלה או סוף, ולהוסיף צעד שלישי: s[::-1] הופך את המחרוזת.
A slice takes a piece of the string: s[start:stop]. The start is included, the stop isn't. You can leave out either end, and add a third step: s[::-1] reverses the string.
isbn = "978-0441172719"
print(isbn[:3])
print(isbn[4:])
print(isbn[-4:])
print("stressed"[::-1])978 0441172719 2719 desserts
צפו בהרצה צעד אחר צעדWatch it run, step by step
מה קורה עכשיוWhat happens now
הקופסאות (משתנים)The boxes (variables)
מסך הפלטOutput screen
חיתוך הוא כמו לחתוך פרוסה מכיכר לחם בעזרת שני סימונים: חותכים בסימון הראשון ועוצרים רגע לפני השני.
Slicing is like cutting a slice from a loaf with two marks: cut at the first mark and stop just before the second.
חיתוך אף פעם לא נותן IndexError: "abc"[1:100] פשוט מחזיר "bc".
Slicing never raises IndexError: "abc"[1:100] just returns "bc".
משתמשים בפסיק במקום נקודתיים.
Using a comma instead of a colon.
isbn = "978-0441172719"
print(isbn[0, 3])Traceback (most recent call last):
File "/Users/you/python-course/slice.py", line 2, in <module>
print(isbn[0, 3])
~~~~^^^^^^
TypeError: string indices must be integers, not 'tuple'TypeError: string indices must be integers: בחיתוך כותבים isbn[0:3] עם נקודתיים.TypeError: string indices must be integers: a slice is written isbn[0:3] with a colon.צפו איפה זה נשברWatch where it breaks
מה קורה עכשיוWhat happens now
הקופסאות (משתנים)The boxes (variables)
מסך הפלטOutput screen
מחרוזת היא שורה של תווים, ואפשר לקחת ממנה חלק.
A string is a row of characters, and you can take a piece of it.
word = "rainbow"
print(word[0])
print(word[-1])
print(word[0:4])
print(word[::-1])r w rain wobniar
צפו בהרצה צעד אחר צעדWatch it run, step by step
מה קורה עכשיוWhat happens now
הקופסאות (משתנים)The boxes (variables)
מסך הפלטOutput screen
03מתודות של מחרוזותString methods
מתודה היא פונקציה ששייכת לערך, וקוראים לה עם נקודה. מתודות של מחרוזת לא משנות את המחרוזת המקורית: הן מחזירות מחרוזת חדשה, כי מחרוזות הן בלתי משתנה (immutable).
A method is a function that belongs to a value, called with a dot. String methods don't change the original string: they return a new one, because strings are immutable.
raw = " the little prince "
clean = raw.strip().title()
print(f"[{clean}]")
print(clean.upper())
print(clean.replace("Little", "Brave"))
print(f"[{raw}]")[The Little Prince] THE LITTLE PRINCE The Brave Prince [ the little prince ]
צפו בהרצה צעד אחר צעדWatch it run, step by step
מה קורה עכשיוWhat happens now
הקופסאות (משתנים)The boxes (variables)
מסך הפלטOutput screen
מתודה היא כמו כפתור על מכשיר: למחרוזת יש כפתורים כמו "נקה" ו"הגדל אותיות". לוחצים עם נקודה, ומקבלים עותק מעובד.
A method is like a button on a device: a string has buttons like "trim" and "uppercase". You press with a dot and get a processed copy.
מה קורה עכשיוWhat happens now
פלטOutput
משתנים (frames)Variables (frames)
אובייקטים בזיכרוןObjects in memory
טעות כתיב בשם המתודה.
A typo in the method name.
print("dune".uppper())Traceback (most recent call last):
File "/Users/you/python-course/methods.py", line 1, in <module>
print("dune".uppper())
^^^^^^^^^^^^^
AttributeError: 'str' object has no attribute 'uppper'. Did you mean: 'upper'?AttributeError: למחרוזת אין מתודה בשם הזה, ו-Python אפילו מציעה את השם הנכון.AttributeError: strings have no method by that name, and Python even suggests the right one.צפו איפה זה נשברWatch where it breaks
מה קורה עכשיוWhat happens now
הקופסאות (משתנים)The boxes (variables)
מסך הפלטOutput screen
משתמשים מקלידים עם רווחים ואותיות גדולות. מתודות מסדרות את זה.
People type with spaces and capitals. Methods tidy that up.
raw = " HeLLo WoRLD "
clean = raw.strip().lower()
print(clean)
print(clean.title())
print(clean.replace("world", "python"))hello world Hello World hello python
צפו בהרצה צעד אחר צעדWatch it run, step by step
מה קורה עכשיוWhat happens now
הקופסאות (משתנים)The boxes (variables)
מסך הפלטOutput screen
04חיפוש בתוך מחרוזתSearching in a string
in בודק אם טקסט מופיע. find מחזירה את המיקום הראשון (או -1 אם אין), count סופרת הופעות, ו-startswith/endswith בודקות התחלה וסוף.
in checks whether text appears. find returns the first position (or -1 if absent), count counts occurrences, and startswith/endswith check the start and end.
email = "noa.levi@example.com"
print("@" in email)
at = email.find("@")
print(at, email[:at], email[at + 1:])
print(email.count("."))
print(email.endswith(".com"))True 8 noa.levi example.com 2 True
צפו בהרצה צעד אחר צעדWatch it run, step by step
מה קורה עכשיוWhat happens now
הקופסאות (משתנים)The boxes (variables)
מסך הפלטOutput screen
find היא כמו לחפש מילה בספר ולקבל מספר עמוד. אם המילה לא שם, מקבלים -1, כמו "אין עמוד כזה".
find is like looking up a word in a book and getting a page number. If it isn't there you get -1, as in "no such page".
משתמשים ב-index במקום find כשהטקסט לא קיים.
Using index instead of find when the text isn't there.
print("hello".index("z"))Traceback (most recent call last):
File "/Users/you/python-course/search.py", line 1, in <module>
print("hello".index("z"))
~~~~~~~~~~~~~^^^^^
ValueError: substring not foundValueError: substring not found: index נכשלת, find מחזירה -1 בשקט.ValueError: substring not found: index fails, find quietly returns -1.צפו איפה זה נשברWatch where it breaks
מה קורה עכשיוWhat happens now
הקופסאות (משתנים)The boxes (variables)
מסך הפלטOutput screen
05עיצוב פלט עם f-stringFormatting output with f-strings
אחרי נקודתיים בתוך {} אפשר לקבוע רוחב ויישור. ככה בונים טבלאות טקסט מסודרות. .2f קובע ספרות אחרי הנקודה, ו-, מוסיף מפריד אלפים.
After a colon inside {} you can set width and alignment. That's how to build tidy text tables. .2f sets decimal places and , adds a thousands separator.
print(f"{'Title':<14}|{'Pages':>6}")
print(f"{'Dune':<14}|{412:>6}")
print(f"{'Emma':<14}|{1036:>6}")
print(f"{1234567:,}")
print(f"[{'hi':^8}]")Title | Pages Dune | 412 Emma | 1036 1,234,567 [ hi ]
צפו בהרצה צעד אחר צעדWatch it run, step by step
מה קורה עכשיוWhat happens now
הקופסאות (משתנים)The boxes (variables)
מסך הפלטOutput screen
עיצוב פלט הוא כמו טבלה במחברת משבצות: כל עמודה תופסת מספר קבוע של משבצות, ולכן הכול מסתדר בקו ישר.
Formatting is like a table on squared paper: each column takes a fixed number of squares, so everything lines up.
מבקשים עיצוב של מספר על מחרוזת.
Asking for number formatting on a string.
price = "19.9"
print(f"{price:.2f}")Traceback (most recent call last):
File "/Users/you/python-course/format.py", line 2, in <module>
print(f"{price:.2f}")
^^^^^^^^^^^
ValueError: Unknown format code 'f' for object of type 'str'ValueError: Unknown format code 'f' for object of type 'str': ממירים קודם: float(price).ValueError: Unknown format code 'f' for object of type 'str': convert first: float(price).צפו איפה זה נשברWatch where it breaks
מה קורה עכשיוWhat happens now
הקופסאות (משתנים)The boxes (variables)
מסך הפלטOutput screen
06תווים מיוחדים ומחרוזות ארוכותSpecial characters and long strings
תו בריחה מתחיל ב-\ ומייצג תו שקשה להקליד: \n שורה חדשה, \t טאב, \\ לוכסן הפוך. לטקסט ארוך על כמה שורות משתמשים בשלוש מירכאות.
An escape character starts with \ and stands for a hard-to-type character: \n newline, \t tab, \\ a backslash. For long text over several lines use triple quotes.
print("שורה 1\nשורה 2")
print("A\tB\tC")
print("She said \"hi\"")
note = """ספר טוב
מחזיק לילה שלם"""
print(note)print("Line 1\nLine 2")
print("A\tB\tC")
print("She said \"hi\"")
note = """A good book
lasts all night"""
print(note)שורה 1 שורה 2 A B C She said "hi" ספר טוב מחזיק לילה שלם
Line 1 Line 2 A B C She said "hi" A good book lasts all night
צפו בהרצה צעד אחר צעדWatch it run, step by step
מה קורה עכשיוWhat happens now
הקופסאות (משתנים)The boxes (variables)
מסך הפלטOutput screen
\ הוא כמו מילה שמסמנת "התו הבא מיוחד": \n הוא לא n, הוא "תרד שורה".
\ is like a word that says "the next character is special": \n isn't n, it means "go to a new line".
מנסים לשנות תו אחד במחרוזת. מחרוזות הן immutable.
Trying to change one character of a string. Strings are immutable.
word = "Dune"
word[0] = "J"Traceback (most recent call last):
File "/Users/you/python-course/escape.py", line 2, in <module>
word[0] = "J"
~~~~^^^
TypeError: 'str' object does not support item assignmentTypeError: 'str' object does not support item assignment: בונים מחרוזת חדשה: "J" + word[1:].TypeError: 'str' object does not support item assignment: build a new string: "J" + word[1:].צפו איפה זה נשברWatch where it breaks
מה קורה עכשיוWhat happens now
הקופסאות (משתנים)The boxes (variables)
מסך הפלטOutput screen
סיימתם את ההרצאה!Lecture complete!
עכשיו המצגת לחזרה מהירה, או ישר לתרגול.
Next: the slides for a quick review, or straight to practice.