לפעמים נרצה שהמחרוזת שלנו תעשה "דברים מיוחדים" – כמו לרדת שורה באמצע המחרוזת או לעשות ריווח גדול באמצעות ↹ TAB (לצורך טבלאות, לדוגמה).
המחשב מתייחס להזחה ולשורה חדשה כתווים של ממש, ועבור כל "תו מיוחד" שכזה יצרו רצף של תווים שמייצג אותו.
לדוגמה, כשנדע מהו רצף התווים שמייצג שורה חדשה, נוכל לכתוב אותו כחלק מהמחרוזת, וכאשר נדפיס אותה נראה ירידת שורה במקום רצף התווים.
נלמד את שני התווים המיוחדים שדיברנו עליהם – \n הוא תו שמסמן ירידת שורה, ו־\t מסמן ריווח גדול.
איך נכניס אותם בקוד? פשוט נשלב אותם כחלק מהמחרוזת במקומות שבהם בא לנו שיופיעו:
In [ ]:
print("Let's print a newline\nVery good. Now let us create a newline\n\twith a nested text!")
רצפי התווים האלו משתמשים בסימן \ ("Backslash", לוכסן שמאלי) כדי לסמן תו מיוחד, והם נפוצים גם בשפות אחרות שאינן פייתון.
נשתמש ב־\' במחרוזת שבה הסימן שמתחיל ומסיים את המחרוזת הוא '. שימוש דומה נעשה עבור \":
In [ ]:
print('It\'s Friday, Friday\nGotta get down on Friday')
In [ ]:
print("Oscar Wild once said: \"Be yourself; everyone else is already taken.\"")
לפעמים גם נרצה פשוט לרשום את התו \. לצורך כך, נשתמש פעמיים בתו הזה.
השוו את שתי המחרוזות הבאות, לדוגמה:
In [ ]:
print("The path of the document is C:\nadia\tofes161\advanced_homework.docx")
In [ ]:
print("The path of the document is C:\\nadia\\tofes161\\advanced_homework.docx")
נוכל גם להבריח את המחרוזת כולה באמצעות התו r לפני המחרוזת, במקרה שאנחנו לא רוצים להשתמש בתווים מיוחדים:
In [ ]:
print(r"The path of the document is C:\nadia\tofes161\advanced_homework.docx")
פייתון, בניגוד לבני אדם, מסתכלת על תווים מיוחדים כמו \n ו־\t כתו אחד.
נסו לבדוק מה ה־len שלהם כדי להיווכח בעצמכם.
פייתון לא מתמודדת טוב עם התו \ בסוף המחרוזת.
אם הגעתם למצב שבו זה קורה, פשוט הבריחו את ה־\ עם \ נוסף.
תרגול:
במשבצת שמתחתיי מצוטט חלק מהנאום המפורסם של מרטין לותר קינג, "I Have A Dream".
הדפיסו אותו בעזרת משפט print בודד.
With this faith we will be able to work together, to pray together, to struggle together, to go to jail together, to stand up for freedom together, knowing that we will be free one day. This will be the day when all of God's children will be able to sing with new meaning, "My country 'tis of thee, sweet land of liberty, of thee I sing. Land where my fathers died, land of the Pilgrims' pride, from every mountainside, let freedom ring."
לפעמים אנחנו פשוט רוצים שפייתון תתמודד עם גוש מלל שהדבקנו.
לפייתון יש פתרון נהדר: היא עובדת גם אם המלל מפוצל לכמה שורות (היא תכניס תווי \n ותפצל לשורות בעצמה), וגם במקרים בהם יש תווים כמו ' או ".
פתרון זה נקרא "מחרוזת קשוחה" (אוקיי, למען האמת, אף אחד לא קורא לה ככה חוץ ממני), וכדי להשתמש בה יש להקליד 3 פעמים את התו " או את התו ' משני צידי המחרוזת.
נראה דוגמה:
In [ ]:
friday_song = """
It's Friday, Friday
Gotta get down on Friday
Everybody's lookin' forward to the weekend, weekend
Friday, Friday
Gettin' down on Friday
Everybody's lookin' forward to the weekend
Partyin', partyin' (Yeah)
Partyin', partyin' (Yeah)
Fun, fun, fun, fun
Lookin' forward to the weekend
It's Friday, Friday
Gotta get down on Friday
Everybody's lookin' forward to the weekend, weekend
Friday, Friday
Gettin' down on Friday
Everybody's lookin' forward to the weekend
"""
print(friday_song)
תרגול:
בשנת 1963 נשא ג'ון קנדי את נאומו "אני ברלינאי". הטקסט המלא שלו מופיע כאן.
השתמשו בפקודת print בודדת כדי להדפיס את הנאום כולו.
עד כה שרשרנו מחרוזות בזהירות בעזרת סימן השרשור +.
דרך נוספת לעשות זאת היא בעזרת fstring, או בשמן המלא, formatted strings.
נראה דוגמה:
In [ ]:
age = 18
name = 'Yam'
שרשור כמו שאנחנו מכירים עד כה:
In [ ]:
print("My age is " + str(age) + " and my name is " + name + ".")
שימוש ב־fstrings:
In [ ]:
print(f"My age is {age} and my name is {name}.")
כדאי לשים לב לנקודות הבאות:
עד כה למדנו פונקציות שעובדות על סוגים שונים של נתונים. אנחנו קוראים להן בשמן, ואז מעבירים להן את הנתון שעליו רוצים לפעול.
type, לדוגמה, יודעת לעבוד על כל נתון שנעביר לה ולהחזיר לנו את הסוג שלו.
רעיון דומה בתכנות נקרא "פעולה", או method (מתודה).
בניגוד לפונקציות, שם הפעולה משויך לסוג הנתון שעליו אנחנו הולכים להפעיל את הפעולה.
בעתיד נלמד לעומק יותר על ההבדלים בין פונקציה לפעולה, והם יישמעו לנו מופשטים פחות. עד אז אתם פטורים מלדעת את הטריוויה הזו.
דבר שכדאי לדעת הוא שהפעולות שנראה עכשיו עובדות רק על מחרוזות, ולא על טיפוסים אחרים.
בשורות הבאות, נשחק עם דוגמאות של פעולות ונראה מה הן עושות בתאים שיבואו לאחר מכן.
אם נבחין בתא שיש צורך להסביר מה קרה בו – יצורף הסבר מעל התא.
פעמים רבות, בין אם בקבלת קלט מהמשתמש ובין אם במחרוזות שקיבלנו ממקור חיצוני כלשהו, נתקל בתווים מיותרים שמקיפים את המחרוזת שלנו.
הפעולה strip עוזרת לנו להסיר אותם.
בצורתה הפשוטה, כשלא מעבירים לה ארגומנטים, היא תסיר את כל הרווחים, האנטרים והטאבים שנמצאים סביב המחרוזת:
In [ ]:
# נסו להכניס הרבה רווחים אחרי או לפני שם המשתמש
username = input("Please enter your user: ")
username = username.strip()
print(f"This string is: {username}.")
כאשר מעבירים לה מחרוזת כארגומנט, היא תבצע את האלגוריתם הבא:
In [ ]:
strange_string = '!@#$%!!!^&This! Is! Sparta!!!!!!!!!&^%$!!!#@!'
print(strange_string.strip('~!@#$%^&*'))
In [ ]:
strange = "This is a very long string which contains strange words, like ululation and lollygag."
נמצא את המקומות שבהם נמצאות המילים המוזרות.
הפעולות find ו־index יחזירו לנו את המיקום (האינדקס) של תת־מחרוזת בתוך מחרוזת אחרת:
In [ ]:
strange.find("ululation")
In [ ]:
strange.find("lollygag")
In [ ]:
strange.index("lollygag")
אז רגע, למה צריך 2 מתודות אם הן עושות אותו דבר?
אם המחרוזת לא נמצאה, find תחזיר לנו -1, בעוד ש־index תחזיר לנו שגיאה.
In [ ]:
strange.find('luculent')
In [ ]:
strange.index('luculent')
הפעולות הללו יחזירו רק את התוצאה הראשונה.
אינטואיטיבית, נראה שנכון תמיד להשתמש בפעולה find, אך אליה וקוץ בה.
כשאנחנו בטוחים שאמורה לחזור תוצאה, עדיף להשתמש ב־index כדי לדעת מאיפה מגיעה השגיאה בתוכנית שלנו ולטפל בה במהירות.
תרגול:
קבלו מהמשתמש שתי מחרוזות.
אם המחרוזת השנייה נמצאת לפני אמצע המחרוזת הראשונה, הדפיסו "Yes!"
אם המחרוזת השנייה לא נמצאת לפני אמצע המחרוזת הראשונה, הדפיסו "No!"
בונוס לגיבורים ולגיבורות: נסו להשתמש בשתי הפעולות, index ו־find.
In [ ]:
test1 = "HeLlO WoRlD 123!"
In [ ]:
test1
In [ ]:
test1.upper()
In [ ]:
test1.lower()
In [ ]:
test1.capitalize() # רק האות הראשונה תהיה גדולה
In [ ]:
test1.title() # מגדיל את האות הראשונה בכל מילה
חשוב לזכור שהפעולות לא משנות את המשתנה.
אם רוצים לשנות אותו, יש להשתמש בהשמה.
In [ ]:
test1
אם נרצה לבדוק כמה פעמים תת־מחרוזת נמצאת בתוך המחרוזת שלנו, נשתמש בפעולה count.
ננסה להבין כמה פעמים מילים מעניינות הופיעו בנאום גטיסברג המפורסם:
In [ ]:
gettysburg_address = """
Four score and seven years ago our fathers brought forth, on this continent, a new nation, conceived in Liberty, and dedicated to the proposition that all men are created equal.
Now we are engaged in a great civil war, testing whether that nation, or any nation so conceived and so dedicated, can long endure. We are met on a great battle-field of that war. We have come to dedicate a portion of that field, as a final resting place for those who here gave their lives that that nation might live. It is altogether fitting and proper that we should do this.
But, in a larger sense, we cannot dedicate—we cannot consecrate—we cannot hallow—this ground. The brave men, living and dead, who struggled here, have consecrated it, far above our poor power to add or detract. The world will little note, nor long remember what we say here, but it can never forget what they did here. It is for us the living, rather, to be dedicated here to the unfinished work which they who fought here have thus far so nobly advanced. It is rather for us to be here dedicated to the great task remaining before us—that from these honored dead we take increased devotion to that cause for which they here gave the last full measure of devotion—that we here highly resolve that these dead shall not have died in vain—that this nation, under God, shall have a new birth of freedom—and that government of the people, by the people, for the people, shall not perish from the earth.
"""
ראשית, נעשה טריק מוכר. נשתמש בפעולה lower כדי להעיף את האותיות הגדולות.
בצורה הזו, count תספור לנו גם את המילים שנכתבו באותיות רישיות:
In [ ]:
gettysburg_address = gettysburg_address.lower()
עכשיו נבדוק כמה פעמים השתמש לינקולן בכל אחת מהמילים: we, nation ו־dedicated.
In [ ]:
gettysburg_address.count('we')
In [ ]:
gettysburg_address.count('dedicated')
In [ ]:
gettysburg_address.count('nation')
פעולה מאוד נפוצה היא replace, שעוזרת לנו להחליף את כל המופעים של תת־מחרוזת אחת באחרת.
לדוגמה, ניקח את הברידג' השני בשיר הנפלא של הביטלס, Hey Jude, ונחליף את כל המופעים של Jude ב־Dude:
In [ ]:
lyrics = """So let it out and let it in, hey Jude, begin
You're waiting for someone to perform with
And don't you know that it's just you, hey Jude, you'll do
The movement you need is on your shoulder
Na na na na na na na na na yeah"""
In [ ]:
lyrics.replace('Jude', 'Dude')
שימו לב לתווים המוזרים באמצע. אלו ירידות השורה שעליהן למדנו בשיעור. אל דאגה – הן לא יופיעו כשנדפיס את המחרוזת.
In [ ]:
print(lyrics.replace('Jude', 'Dude'))
רק נזכיר שהפעולה לא משנה את המחרוזת עצמה, וכדי לשנות אותה נצטרך לבצע השמה.
In [ ]:
lyrics = """So let it out and let it in, hey Jude, begin
You're waiting for someone to perform with
And don't you know that it's just you, hey Jude, you'll do
The movement you need is on your shoulder
Na na na na na na na na na yeah"""
print("Before: ")
lyrics.replace('Jude', 'Dude')
print(lyrics)
lyrics = lyrics.replace('Jude', 'Dude')
print('-' * 50)
print("After: ")
print(lyrics)
לעיתים קרובות נרצה להפריד את הטקסט שלנו לחלקים.
הפעולה split מאפשרת לנו לעשות את זה, ולקבל רשימה של האיברים המופרדים:
In [ ]:
i_like_to_eat = 'chocolate, fudge, cream, cookies, banana, hummus'
In [ ]:
i_like_to_eat.split(', ')
בסוגריים כתבנו מה אנחנו רוצים שיהיה התו, או סדרת התווים, שתהיה אחראית להפרדה בין האיברים.
שימו לב שקיבלנו רשימה לכל דבר:
In [ ]:
type(i_like_to_eat.split(', '))
In [ ]:
i_like_to_eat.split(', ')[0]
דרך נוספת להשתמש ב־split היא לא להעביר לה כלום ברשימת הארגומנטים.
במקרה כזה, split תפצל לנו את המחרוזת לפי רווחים, שורות חדשות וטאבים.
In [ ]:
some_paragraph = """
Gadsby is a 1939 novel by Ernest Vincent Wright written as a lipogram, which does not include words that contain the letter E. The plot revolves around the dying fictional city of Branton Hills, which is revitalized as a result of the efforts of protagonist John Gadsby and a youth group he organizes.
Though vanity published and little noticed in its time, the book is a favourite of fans of constrained writing and is a sought-after rarity among some book collectors. Later editions of the book have sometimes carried the alternative subtitle 50,000 Word Novel Without the Letter "E".
Despite Wright's claim, published versions of the book may contain a handful of uses of the letter "e". The version on Project Gutenberg, for example, contains "the" three times and "officers" once.
"""
In [ ]:
some_paragraph.split()
הפעולה הזו שימושית בטירוף ונראה אותה עוד הרבה.
היא מאפשרת לנו לקבל מידע רב על כמות גדולה של מלל.
לפעמים אנחנו רוצים לעשות את הפעולה ההפוכה מפיצול – איחוד!
הפעולה join מקבלת כארגומנט רשימה, ופועלת על המחרוזת שתחבר בין איבר לאיבר.
נראה דוגמה:
In [ ]:
i_love_to_eat = ['chocolate', 'fudge', 'cream', 'cookies', 'banana', 'hummus']
thing_to_join_by = ", "
thing_to_join_by.join(i_love_to_eat)
ואם אנחנו כבר שם, קצת כבוד לספר הישראלי, הכבש השישה־עשר:
In [ ]:
what_i_love = ["שוקולד", "עוגות גבינה", "ארטיק", "סוכריות", "תות גינה"]
vav_ha_hibur = ' ו'
song = "אני אוהב " + vav_ha_hibur.join(what_i_love)
print(song)
אחד הטריקים השימושיים הוא לבדוק אם המחרוזת שלנו מתחילה או מסתיימת בתת־מחרוזת אחרת.
In [ ]:
some_test = "Hello, my name is Inigo Montoya, you killed my father, prepare to die!"
In [ ]:
is_welcoming = some_test.startswith('Hello,')
print(is_welcoming)
In [ ]:
is_shouting = some_test.endswith('!')
print(is_shouting)
In [ ]:
is_goodbye = some_test.endswith("Goodbye, my kind sir.")
print(is_goodbye)
In [ ]:
address = "Python Street 5, Hadera, Israel"
print("Does the user live in Python Street?... " + str(address.startswith('Python Street')))
print("Does the user live in Scotland?... " + str(address.endswith('Scotland')))
תרגול:
קבלו מהמשתמש נתיב לקובץ מסוים שנמצא על המחשב שלו, ובדקו האם הסיומת שלו היא .docx
הדפיסו לו הודעה מתאימה.
דוגמה לנתיב תקין: C:\My Documents\Resume.docx.
יש נטייה לשכוח את ה־s אחרי ה־end או את ה־start ב־endswith וב־startswith.
נוכל גם לבדוק אם המחרוזת שלנו היא מסוג מסוים:
In [ ]:
test2 = "HELLO WORLD"
print("test2.isalnum(): " + str(test2.isalnum()))
print("test2.isalpha(): " + str(test2.isalpha()))
print("test2.isdecimal(): " + str(test2.isdecimal()))
In [ ]:
test3 = "12345"
print("test3.isalnum(): " + str(test3.isalnum()))
print("test3.isalpha(): " + str(test3.isalpha()))
print("test3.isdecimal(): " + str(test3.isdecimal()))
In [ ]:
test4 = "HELLOWORLD"
print("test4.isalnum(): " + str(test4.isalnum()))
print("test4.isalpha(): " + str(test4.isalpha()))
print("test4.isdecimal(): " + str(test4.isdecimal()))
In [ ]:
test5 = "ABC123"
print("test5.isalnum(): " + str(test5.isalnum()))
print("test5.isalpha(): " + str(test5.isalpha()))
print("test5.isdecimal(): " + str(test5.isdecimal()))
השתמשו בטקסט של נאום גטיסברג ובדקו כמה מילים יש בו.
בדקו כמה פעמים הופיעו המילים we, here, great, nation ו־dedicated, וחשבו מה שיעורן באחוזים בטקסט כולו.
In [ ]:
gettysburg_address = """
Four score and seven years ago our fathers brought forth, on this continent, a new nation, conceived in Liberty, and dedicated to the proposition that all men are created equal.
Now we are engaged in a great civil war, testing whether that nation, or any nation so conceived and so dedicated, can long endure. We are met on a great battle-field of that war. We have come to dedicate a portion of that field, as a final resting place for those who here gave their lives that that nation might live. It is altogether fitting and proper that we should do this.
But, in a larger sense, we cannot dedicate—we cannot consecrate—we cannot hallow—this ground. The brave men, living and dead, who struggled here, have consecrated it, far above our poor power to add or detract. The world will little note, nor long remember what we say here, but it can never forget what they did here. It is for us the living, rather, to be dedicated here to the unfinished work which they who fought here have thus far so nobly advanced. It is rather for us to be here dedicated to the great task remaining before us—that from these honored dead we take increased devotion to that cause for which they here gave the last full measure of devotion—that we here highly resolve that these dead shall not have died in vain—that this nation, under God, shall have a new birth of freedom—and that government of the people, by the people, for the people, shall not perish from the earth.
"""
כדי לחשב את שיעורן באחוזים: סִכְמוּ את מספר הפעמים שכל מילה מופיעה בטקסט. הכפילו מספר זה במאה וחלקו בסך המילים בטקסט.
קבלו מהמשתמש מילה מסוימת ומשפט.
בדקו שתחילת המילה מופיעה לפני החצי של המשפט.
היעזרו בדוגמאות כדי לבדוק את עצמכם.
בספר המרתק של ג'ורג' אורוול, 1984, הסלוגן של מפלגת השלטון הוא מלחמה היא שלום, חירות היא עבדות, בורות היא כוח
.
קבלו טקסט מהמשתמש, והחליפו את המילים לפי המילון הבא:
לצורך התרגיל, הניחו שהקלט שהזין המשתמש הוא באותיות קטנות בלבד.