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

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

מחרוזותStrings

אינדקסים, חיתוך, מתודות של מחרוזות ועיצוב פלט.

Indexing, slicing, string methods and formatting output.

או Ctrl+Por Ctrl+P

הנקודות החשובותKey points

  • הספירה מתחילה ב-0Counting starts at 0
  • s[-1] הוא התו האחרוןs[-1] is the last character
  • s[a:b] מ-a עד לפני bs[a:b] from a up to (not incl.) b
  • s[:3] ההתחלה, s[3:] ההמשךs[:3] the start, s[3:] the rest
  • .strip() מנקה רווחים בקצוות.strip() trims spaces at the ends
  • .upper() .lower() .title().upper() .lower() .title()
  • "a" in s → True/False"a" in s → True/False
  • .find() מחזיר מיקום או -1.find() returns a position or -1
  • {x:<10} יישור לשמאל ברוחב 10{x:<10} left-align, width 10

מונחיםTerms

  • אינדקסindex: מספר המקום של פריט ברצף. מתחילים מ-0, ו--1 הוא האחרון.The position number of an item in a sequence. Starts at 0, and -1 is the last.
  • חיתוך (slice)slice: לקיחת חלק מרצף: s[start:stop:step]. ה-stop לא נכלל.Taking part of a sequence: s[start:stop:step]. The stop isn't included.
  • מתודהmethod: פונקציה ששייכת לערך ונקראת עם נקודה, כמו name.upper().A function that belongs to a value and is called with a dot, like name.upper().
  • בלתי משתנה (immutable)immutable: ערך שאי אפשר לשנות במקום. מחרוזות, מספרים וטאפלים הם immutable.A value that can't be changed in place. Strings, numbers and tuples are immutable.
  • תו בריחהescape character: צירוף שמתחיל ב-\ ומייצג תו מיוחד, כמו \n (שורה חדשה).A sequence starting with \ that stands for a special character, like \n (newline).

Cheatsheet

אינדקסיםIndexing
word = "Python"
print(word[0], word[1], word[-1])
print(len(word))
print(word[len(word) - 1])
חיתוךSlicing
isbn = "978-0441172719"
print(isbn[:3])
print(isbn[4:])
print(isbn[-4:])
print("stressed"[::-1])
מתודותMethods
raw = "   the little prince  "
clean = raw.strip().title()
print(f"[{clean}]")
print(clean.upper())
print(clean.replace("Little", "Brave"))
print(f"[{raw}]")
חיפושSearching
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"))
עיצובFormatting
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}]")
תווים מיוחדיםSpecial characters
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)

שגיאות שפגשנוErrors we met

שגיאהErrorמה זה אומרWhat it meansמה עושיםWhat to do
IndexErrorפונים לאינדקס שלא קיים. ב-"Python" יש 6 תווים, אז האינדקס האחרון הוא 5.Asking for an index that doesn't exist. "Python" has 6 characters, so the last index is 5.IndexError: string index out of range: האינדקס הגבוה ביותר הוא len(word) - 1.IndexError: string index out of range: the highest index is len(word) - 1.
TypeErrorמשתמשים בפסיק במקום נקודתיים.Using a comma instead of a colon.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.
AttributeErrorטעות כתיב בשם המתודה.A typo in the method name.AttributeError: למחרוזת אין מתודה בשם הזה, ו-Python אפילו מציעה את השם הנכון.AttributeError: strings have no method by that name, and Python even suggests the right one.
ValueErrorמשתמשים ב-index במקום find כשהטקסט לא קיים.Using index instead of find when the text isn't there.ValueError: substring not found: index נכשלת, find מחזירה -1 בשקט.ValueError: substring not found: index fails, find quietly returns -1.
ValueErrorמבקשים עיצוב של מספר על מחרוזת.Asking for number formatting on a string.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).
TypeErrorמנסים לשנות תו אחד במחרוזת. מחרוזות הן immutable.Trying to change one character of a string. Strings are immutable.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:].

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