נבנה על ידיBuilt by Ariel Yohimovich

PythonPython
4
חלקPart 1: יסודותFoundations כ-3 שעות (כולל הפסקה)About 3 hours (with a break)

מחרוזות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.

index.py
word = "Python"
print(word[0], word[1], word[-1])
print(len(word))
print(word[len(word) - 1])
פלטOutput
P y n
6
n
צפו בהרצה צעד אחר צעדWatch it run, step by step
צפו בהרצהWatch it runשורה אחרי שורה, כמו ש-Python קוראתLine by line, the way Python reads it

מה קורה עכשיוWhat happens now

הקופסאות (משתנים)The boxes (variables)

מסך הפלטOutput screen

אנלוגיה מהחייםReal-life analogy

אינדקס הוא כמו מספר מושב בשורה בקולנוע, רק שהמושב הראשון הוא 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.

טעות נפוצהCommon mistake

פונים לאינדקס שלא קיים. ב-"Python" יש 6 תווים, אז האינדקס האחרון הוא 5.

Asking for an index that doesn't exist. "Python" has 6 characters, so the last index is 5.

index.py
word = "Python"
print(word[6])
מה Python עונהWhat Python says
Traceback (most recent call last):
  File "/Users/you/python-course/index.py", line 2, in <module>
    print(word[6])
          ~~~~^^^
IndexError: string index out of range
בעברית פשוטה: In plain words: IndexError: 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
איפה זה נשברWhere it breaksשורה אחרי שורה, כמו ש-Python קוראתLine by line, the way Python reads it

מה קורה עכשיו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.

slice.py
isbn = "978-0441172719"
print(isbn[:3])
print(isbn[4:])
print(isbn[-4:])
print("stressed"[::-1])
פלטOutput
978
0441172719
2719
desserts
צפו בהרצה צעד אחר צעדWatch it run, step by step
צפו בהרצהWatch it runשורה אחרי שורה, כמו ש-Python קוראתLine by line, the way Python reads it

מה קורה עכשיוWhat happens now

הקופסאות (משתנים)The boxes (variables)

מסך הפלטOutput screen

אנלוגיה מהחייםReal-life analogy

חיתוך הוא כמו לחתוך פרוסה מכיכר לחם בעזרת שני סימונים: חותכים בסימון הראשון ועוצרים רגע לפני השני.

Slicing is like cutting a slice from a loaf with two marks: cut at the first mark and stop just before the second.

טיפTip

חיתוך אף פעם לא נותן IndexError: "abc"[1:100] פשוט מחזיר "bc".

Slicing never raises IndexError: "abc"[1:100] just returns "bc".

טעות נפוצהCommon mistake

משתמשים בפסיק במקום נקודתיים.

Using a comma instead of a colon.

slice.py
isbn = "978-0441172719"
print(isbn[0, 3])
מה Python עונהWhat Python says
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'
בעברית פשוטה: In plain words: 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
איפה זה נשברWhere it breaksשורה אחרי שורה, כמו ש-Python קוראתLine by line, the way Python reads it

מה קורה עכשיוWhat happens now

הקופסאות (משתנים)The boxes (variables)

מסך הפלטOutput screen

מחרוזת היא שורה של תווים, ואפשר לקחת ממנה חלק.

A string is a row of characters, and you can take a piece of it.

עוד דוגמה: חותכים שםOne more: slicing a name
example.py
word = "rainbow"
print(word[0])
print(word[-1])
print(word[0:4])
print(word[::-1])
פלטOutput
r
w
rain
wobniar
צפו בהרצה צעד אחר צעדWatch it run, step by step
צפו בהרצהWatch it runשורה אחרי שורה, כמו ש-Python קוראתLine by line, the way Python reads it

מה קורה עכשיו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.

methods.py
raw = "   the little prince  "
clean = raw.strip().title()
print(f"[{clean}]")
print(clean.upper())
print(clean.replace("Little", "Brave"))
print(f"[{raw}]")
פלטOutput
[The Little Prince]
THE LITTLE PRINCE
The Brave Prince
[   the little prince  ]
צפו בהרצה צעד אחר צעדWatch it run, step by step
צפו בהרצהWatch it runשורה אחרי שורה, כמו ש-Python קוראתLine by line, the way Python reads it

מה קורה עכשיוWhat happens now

הקופסאות (משתנים)The boxes (variables)

מסך הפלטOutput screen

אנלוגיה מהחייםReal-life analogy

מתודה היא כמו כפתור על מכשיר: למחרוזת יש כפתורים כמו "נקה" ו"הגדל אותיות". לוחצים עם נקודה, ומקבלים עותק מעובד.

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.

ויזואלייזר זיכרוןMemory visualizerמחרוזות לא משתנות: נוצרות חדשותStrings don't change: new ones are made

מה קורה עכשיוWhat happens now

פלטOutput

משתנים (frames)Variables (frames)

אובייקטים בזיכרוןObjects in memory

טעות נפוצהCommon mistake

טעות כתיב בשם המתודה.

A typo in the method name.

methods.py
print("dune".uppper())
מה Python עונהWhat Python says
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'?
בעברית פשוטה: In plain words: AttributeError: למחרוזת אין מתודה בשם הזה, ו-Python אפילו מציעה את השם הנכון.AttributeError: strings have no method by that name, and Python even suggests the right one.
צפו איפה זה נשברWatch where it breaks
איפה זה נשברWhere it breaksשורה אחרי שורה, כמו ש-Python קוראתLine by line, the way Python reads it

מה קורה עכשיוWhat happens now

הקופסאות (משתנים)The boxes (variables)

מסך הפלטOutput screen

משתמשים מקלידים עם רווחים ואותיות גדולות. מתודות מסדרות את זה.

People type with spaces and capitals. Methods tidy that up.

עוד דוגמה: מנקים קלטOne more: cleaning input
example.py
raw = "   HeLLo WoRLD  "
clean = raw.strip().lower()
print(clean)
print(clean.title())
print(clean.replace("world", "python"))
פלטOutput
hello world
Hello World
hello python
צפו בהרצה צעד אחר צעדWatch it run, step by step
צפו בהרצהWatch it runשורה אחרי שורה, כמו ש-Python קוראתLine by line, the way Python reads it

מה קורה עכשיו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.

format.py
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}]")
פלטOutput
Title         | Pages
Dune          |   412
Emma          |  1036
1,234,567
[   hi   ]
צפו בהרצה צעד אחר צעדWatch it run, step by step
צפו בהרצהWatch it runשורה אחרי שורה, כמו ש-Python קוראתLine by line, the way Python reads it

מה קורה עכשיוWhat happens now

הקופסאות (משתנים)The boxes (variables)

מסך הפלטOutput screen

אנלוגיה מהחייםReal-life analogy

עיצוב פלט הוא כמו טבלה במחברת משבצות: כל עמודה תופסת מספר קבוע של משבצות, ולכן הכול מסתדר בקו ישר.

Formatting is like a table on squared paper: each column takes a fixed number of squares, so everything lines up.

טעות נפוצהCommon mistake

מבקשים עיצוב של מספר על מחרוזת.

Asking for number formatting on a string.

format.py
price = "19.9"
print(f"{price:.2f}")
מה Python עונהWhat Python says
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'
בעברית פשוטה: In plain words: 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
איפה זה נשברWhere it breaksשורה אחרי שורה, כמו ש-Python קוראתLine by line, the way Python reads it

מה קורה עכשיו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.

escape.py
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)
פלטOutput
שורה 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
צפו בהרצהWatch it runשורה אחרי שורה, כמו ש-Python קוראתLine by line, the way Python reads it

מה קורה עכשיוWhat happens now

הקופסאות (משתנים)The boxes (variables)

מסך הפלטOutput screen

אנלוגיה מהחייםReal-life analogy

\ הוא כמו מילה שמסמנת "התו הבא מיוחד": \n הוא לא n, הוא "תרד שורה".

\ is like a word that says "the next character is special": \n isn't n, it means "go to a new line".

טעות נפוצהCommon mistake

מנסים לשנות תו אחד במחרוזת. מחרוזות הן immutable.

Trying to change one character of a string. Strings are immutable.

escape.py
word = "Dune"
word[0] = "J"
מה Python עונהWhat Python says
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 assignment
בעברית פשוטה: In plain words: TypeError: '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
איפה זה נשברWhere it breaksשורה אחרי שורה, כמו ש-Python קוראתLine by line, the way Python reads it

מה קורה עכשיוWhat happens now

הקופסאות (משתנים)The boxes (variables)

מסך הפלטOutput screen

סיימתם את ההרצאה!Lecture complete!

עכשיו המצגת לחזרה מהירה, או ישר לתרגול.

Next: the slides for a quick review, or straight to practice.

נבנה על ידיBuilt by Ariel Yohimovich