נבנה על ידיBuilt by Ariel Yohimovich
s[-1] הוא התו האחרוןs[-1] is the last characterlen(s) = מספר התוויםlen(s) = number of characters-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])word = "Python"
print(word[0], word[1], word[-1])
print(len(word))
print(word[len(word) - 1])P y n 6 n
-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.word = "Python"
print(word[6])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.s[a:b] מ-a עד לפני bs[a:b] from a up to (not incl.) bs[:3] ההתחלה, s[3:] ההמשךs[:3] the start, s[3:] the rests[::-1] הפוךs[::-1] reverseds[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])isbn = "978-0441172719"
print(isbn[:3])
print(isbn[4:])
print(isbn[-4:])
print("stressed"[::-1])978 0441172719 2719 desserts
isbn = "978-0441172719"
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..strip() מנקה רווחים בקצוות.strip() trims spaces at the ends.upper() .lower() .title().upper() .lower() .title().replace(a, b) מחליף.replace(a, b) replacesraw = " the little prince "
clean = raw.strip().title()
print(f"[{clean}]")
print(clean.upper())
print(clean.replace("Little", "Brave"))
print(f"[{raw}]")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 ]
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."a" in s → True/False"a" in s → True/False.find() מחזיר מיקום או -1.find() returns a position or -1.count() .startswith().count() .startswith()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"))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
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".print("hello".index("z"))ValueError: substring not found
ValueError: substring not found: index נכשלת, find מחזירה -1 בשקט.ValueError: substring not found: index fails, find quietly returns -1.index במקום find כשהטקסט לא קיים.Using index instead of find when the text isn't there.{x:<10} יישור לשמאל ברוחב 10{x:<10} left-align, width 10{x:>5} לימין, {x:^9} למרכז{x:>5} right, {x:^9} center{n:,} מפריד אלפים{n:,} thousands separator{} אפשר לקבוע רוחב ויישור. ככה בונים טבלאות טקסט מסודרות. .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}]")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 ]
price = "19.9"
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).\n שורה חדשה, \t טאב\n newline, \t tab\" מירכאות בתוך מירכאות\" quotes inside quotes"""...""" מחרוזת רב-שורתית"""...""" multi-line string\ ומייצג תו שקשה להקליד: \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)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
\ הוא כמו מילה שמסמנת "התו הבא מיוחד": \n הוא לא n, הוא "תרד שורה".\ is like a word that says "the next character is special": \n isn't n, it means "go to a new line".word = "Dune"
word[0] = "J"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:].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נבנה על ידיBuilt by Ariel Yohimovich