Get started learning Python with DataCamp's free Intro to Python tutorial. Learn Data Science by completing interactive coding challenges and watching videos by expert instructors. Start Now!

This site is generously supported by DataCamp. DataCamp offers online interactive Python Tutorials for Data Science. Join 11 million other learners and get started learning Python for data science today!

Good news! You can save 25% off your Datacamp annual subscription with the code LEARNPYTHON23ALE25 - Click here to redeem your discount

עיצוב מחרוזות


Python משתמשת בעיצוב מחרוזות בסגנון C כדי ליצור מחרוזות חדשות ומעוצבות. האופרטור "%" משמש לעצב קבוצה של משתנים הכלולים ב"tuple" (רשימה בגודל קבוע), יחד עם מחרוזת תבנית, המכילה טקסט רגיל יחד עם "מפרטי ארגומנטים", סמלים מיוחדים כמו "%s" ו- "%d".

נניח שיש לך משתנה בשם "name" עם שם המשתמש שלך בו, ואז תרצה להדפיס (ברכה למשתמש הזה.)

# זה ידפיס "Hello, John!"
name = "John"
print("Hello, %s!" % name)

כדי להשתמש בשני מפרטי ארגומנטים או יותר, השתמש ב-tuple (סוגריים):

# זה ידפיס "John is 23 years old."
name = "John"
age = 23
print("%s is %d years old." % (name, age))

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

# זה ידפיס: A list: [1, 2, 3]
mylist = [1,2,3]
print("A list: %s" % mylist)

הנה כמה מפרטי ארגומנטים בסיסיים שכדאי לדעת:

%s - מחרוזת (או כל אובייקט בעל ייצוג מחרוזת, כמו מספרים)

%d - מספרים שלמים

%f - מספרים עשרוניים

%.<מספר ספרות>f - מספרים עשרוניים עם כמות קבועה של ספרות מימין לנקודה.

%x/%X - מספרים שלמים בייצוג הקסה (אותיות קטנות/גדולות)

תרגיל

תצטרכו לכתוב מחרוזת תבנית שתדפיס את הנתונים באמצעות התחביר הבא: Hello John Doe. Your current balance is $53.44.

data = ("John", "Doe", 53.44) format_string = "Hello" print(format_string % data) data = ("John", "Doe", 53.44) format_string = "Hello %s %s. Your current balance is $%s." print(format_string % data) #test_output_contains("Hello John Doe. Your current balance is $53.44.", no_output_msg= "Make sure you add the `%s` in the correct spaces to the `format_string` to meeet the exercise goals!") test_object('format_string') success_msg('Great work!')

This site is generously supported by DataCamp. DataCamp offers online interactive Python Tutorials for Data Science. Join over a million other learners and get started learning Python for data science today!

Previous Tutorial Next Tutorial Take the Test
Copyright © learnpython.org. Read our Terms of Use and Privacy Policy