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

חזרה למפגשBack
PythonPython

מחרוזותStrings

מפגש 4: אינדקסים, חיתוך, מתודות של מחרוזות ועיצוב פלט.Session 4: Indexing, slicing, string methods and formatting output.

מה נעשה היוםToday's plan

  • אינדקסיםIndexing
  • חיתוךSlicing
  • מתודותMethods
  • חיפושSearching
  • עיצובFormatting
  • תווים מיוחדיםSpecial characters
נושאTopic 1

אינדקסיםIndexing

אינדקסים ו-lenIndexing and len

  • הספירה מתחילה ב-0Counting starts at 0
  • s[-1] הוא התו האחרוןs[-1] is the last character
  • len(s) = מספר התוויםlen(s) = number of characters
שאלה לכיתהQuestion for the class

מה ידפיס הקוד?What will this print?

python
word = "Python"
print(word[0], word[1], word[-1])
print(len(word))
print(word[len(word) - 1])

    אינדקסיםIndexing

    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

    אנלוגיה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

    index.py
    word = "Python"
    print(word[6])
    מה Python עונהWhat Python says
    IndexError: string index out of range
    IndexError: string index out of range: האינדקס הגבוה ביותר הוא len(word) - 1.IndexError: string index out of range: the highest index is len(word) - 1.
    נושאTopic 2

    חיתוךSlicing

    חיתוך מחרוזותSlicing

    • 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
    • s[::-1] הפוךs[::-1] reversed
    שאלה לכיתהQuestion for the class

    מה ידפיס הקוד?What will this print?

    python
    isbn = "978-0441172719"
    print(isbn[:3])
    print(isbn[4:])
    print(isbn[-4:])
    print("stressed"[::-1])

      חיתוךSlicing

      slice.py
      isbn = "978-0441172719"
      print(isbn[:3])
      print(isbn[4:])
      print(isbn[-4:])
      print("stressed"[::-1])
      פלטOutput
      978
      0441172719
      2719
      desserts

      אנלוגיהAnalogy

      חיתוך הוא כמו לחתוך פרוסה מכיכר לחם בעזרת שני סימונים: חותכים בסימון הראשון ועוצרים רגע לפני השני.Slicing is like cutting a slice from a loaf with two marks: cut at the first mark and stop just before the second.

      טעות נפוצהCommon mistake

      slice.py
      isbn = "978-0441172719"
      print(isbn[0, 3])
      מה Python עונהWhat Python says
      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.
      נושאTopic 3

      מתודותMethods

      מתודות של מחרוזותString methods

      • .strip() מנקה רווחים בקצוות.strip() trims spaces at the ends
      • .upper() .lower() .title().upper() .lower() .title()
      • .replace(a, b) מחליף.replace(a, b) replaces
      שאלה לכיתהQuestion for the class

      מה ידפיס הקוד?What will this print?

      python
      raw = "   the little prince  "
      clean = raw.strip().title()
      print(f"[{clean}]")
      print(clean.upper())
      print(clean.replace("Little", "Brave"))
      print(f"[{raw}]")

        מתודותMethods

        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  ]

        אנלוגיה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.

        טעות נפוצהCommon mistake

        methods.py
        print("dune".uppper())
        מה Python עונהWhat Python says
        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.
        נושאTopic 4

        חיפושSearching

        חיפוש בתוך מחרוזתSearching in a string

        • "a" in s → True/False"a" in s → True/False
        • .find() מחזיר מיקום או -1.find() returns a position or -1
        • .count() .startswith().count() .startswith()
        שאלה לכיתהQuestion for the class

        מה ידפיס הקוד?What will this print?

        python
        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"))

          חיפושSearching

          search.py
          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"))
          פלטOutput
          True
          8 noa.levi example.com
          2
          True

          אנלוגיהAnalogy

          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".

          טעות נפוצהCommon mistake

          search.py
          print("hello".index("z"))
          מה Python עונהWhat Python says
          ValueError: substring not found
          ValueError: substring not found: index נכשלת, find מחזירה -1 בשקט.ValueError: substring not found: index fails, find quietly returns -1.
          נושאTopic 5

          עיצובFormatting

          עיצוב פלט עם f-stringFormatting output with f-strings

          • {x:<10} יישור לשמאל ברוחב 10{x:<10} left-align, width 10
          • {x:>5} לימין, {x:^9} למרכז{x:>5} right, {x:^9} center
          • {n:,} מפריד אלפים{n:,} thousands separator
          שאלה לכיתהQuestion for the class

          מה ידפיס הקוד?What will this print?

          python
          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}]")

            עיצובFormatting

            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   ]

            אנלוגיהAnalogy

            עיצוב פלט הוא כמו טבלה במחברת משבצות: כל עמודה תופסת מספר קבוע של משבצות, ולכן הכול מסתדר בקו ישר.Formatting is like a table on squared paper: each column takes a fixed number of squares, so everything lines up.

            טעות נפוצהCommon mistake

            format.py
            price = "19.9"
            print(f"{price:.2f}")
            מה Python עונהWhat Python says
            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).
            נושאTopic 6

            תווים מיוחדיםSpecial characters

            תווים מיוחדים ומחרוזות ארוכותSpecial characters and long strings

            • \n שורה חדשה, \t טאב\n newline, \t tab
            • \" מירכאות בתוך מירכאות\" quotes inside quotes
            • """...""" מחרוזת רב-שורתית"""...""" multi-line string
            שאלה לכיתהQuestion for the class

            מה ידפיס הקוד?What will this print?

            python
            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)

              תווים מיוחדיםSpecial characters

              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

              אנלוגיה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

              escape.py
              word = "Dune"
              word[0] = "J"
              מה Python עונהWhat Python says
              TypeError: 'str' object does not support item assignment
              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:].

              מה למדנוWhat we learned

              • הספירה מתחילה ב-0Counting starts at 0
              • s[a:b] מ-a עד לפני bs[a:b] from a up to (not incl.) b
              • .strip() מנקה רווחים בקצוות.strip() trims spaces at the ends
              • "a" in s → True/False"a" in s → True/False
              • {x:<10} יישור לשמאל ברוחב 10{x:<10} left-align, width 10
              • \n שורה חדשה, \t טאב\n newline, \t tab

              עכשיו לתרגולNow, practice

              5 תרגילים ו-2 אתגרים, עם בדיקה אוטומטית5 exercises and 2 challenges, auto-checked
              הערות מרצהSpeaker notes

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