![[Formales]] ![[zImagesCloud/string_formatting_newly_married__winterstyle_060.png]] [Python String format() Method](https://www.w3schools.com/python/ref_string_format.asp)<br> In: *W3 Schools* > [!NOTE] Exercises; Context: Newly Married Couple # Overview <!--Bild hinzufügen--> The upcoming exercises are focused on a newly married couple. You'll explore various Python string formatting methods through engaging diary entry exercises. Each technique, from basic concatenation to advanced f-strings, uniquely documents the couple's daily adventures, memorable moments, and dreams. 1. Concatenation with **+** simplifies joining date, location, and event strings for a straightforward diary entry. 2. F-strings enhance entries by dynamically inserting expressions, like calculating days since the wedding. 3. **str.format()** offers flexibility for entries that rate the day and detail memorable moments. 4. Old style **%** formatting and template strings provide alternatives for documenting surprises and gifts, balancing readability with security. 5. Advanced f-strings allow embedding expressions and formatting costs, while multi-line f-strings are perfect for vivid dream descriptions. This concise exploration equips you with the right string formatting tools to capture the essence of married life in Python vividly, blending functionality with creativity. # Concatenation with + ## Objective Write a diary entry combining separate strings that detail the day's events, including date, location, and a brief event description. ## Dataset ```python from faker import Faker import random faker = Faker() date = faker.date() location = faker.city() event = random.choice(['Went for a walk', 'Visited a museum', 'Tried a new restaurant']) entry = "Date: " + date + ". Location: " + location + ". Event: " + event + "." print(entry) ``` ## Solution ```python # Assuming variables date, location, and event are already defined entry = "Date: " + date + ". Location: " + location + ". Event: " + event + "." print(entry) ``` ## Explanation This solution directly concatenates various strings that make up the diary entry, including the date, location, and the day's main event. The + operator joins these strings with appropriate punctuation and spacing for readability. # String Interpolation (f-strings) ![[zImagesCloud/string_interpolation.png]] ## Objective Format a diary entry that includes dynamic expressions calculating the days since the wedding and what the couple did. ## Dataset ```python from datetime import datetime, timedelta wedding_date = datetime.now() - timedelta(days=random.randint(50, 150)) activity = random.choice(['cooking class', 'dance lesson', 'movie night']) current_date = datetime.now() days_since_wedding = (current_date - wedding_date).days entry = f"Days since wedding: {days_since_wedding}. Today's activity: {activity}." print(entry) ``` ## Solution ```python # Assuming variables wedding_date, activity, and current_date are defined days_since_wedding = (current_date - wedding_date).days entry = f"Days since wedding: {days_since_wedding}. Today's activity: {activity}." print(entry) ``` ## Explanation F-strings allow for direct insertion of Python expressions inside string literals. Here, days_since_wedding is calculated as part of the f-string, and both this value and the day's activity are dynamically included in the formatted string. # str.format() ![[zImagesCloud/str_format.png]] ## Objective Create a formatted diary entry where the couple rates their day out of 10 and describes the best moment. ## Dataset ```python rating = random.randint(1, 10) best_moment = faker.sentence() entry = "Today's rating: {}. The best moment was: {}.".format(rating, best_moment) print(entry) ``` ## Solution ```python # Assuming variables rating and best_moment are defined entry = "Today's rating: {}. The best moment was: {}.".format(rating, best_moment) print(entry) ``` ## Explanation The str.format() method inserts the day's rating and the best moment into placeholders within the string. This method offers a readable and flexible way to format strings, especially useful when the order of variables is essential or when using the exact variable multiple times. # Old Style working with % ![[zImagesCloud/old_style.png]] ## Objective Document a surprising event for the couple, including the time and the event description. ## Dataset ```python time = faker.time() surprise_event = random.choice(['found a lost kitten', 'saw a shooting star', 'met an old friend unexpectedly']) entry = "At %s, we %s." % (time, surprise_event) print(entry) ``` ## Solution ```python # Assuming variables time and surprise_event are defined entry = "At %s, we %s." % (time, surprise_event) print(entry) ``` ## Explanation This solution uses the % operator for string formatting, an older style that Python supports. The corresponding variables replace the %s format specifier in order, provided as a tuple after the % operator. This method is less preferred due to less readability and flexibility than newer methods. # Template Strings ## Objective Write a diary entry about a gift one gave to the other, using template strings for flexibility and security. ## Dataset ```python from string import Template giver = random.choice(['Husband', 'Wife']) gift = faker.word() template = Template("$giver gave a $gift as a surprise.") entry = template.substitute(giver=giver, gift=gift) print(entry) ``` ## Solution ```python # Assuming variables giver and gift are defined from string import Template template = Template("$giver gave a $gift as a surprise.") entry = template.substitute(giver=giver, gift=gift) print(entry) ``` ## Explanation Template strings provide a more straightforward and secure way to interpolate. Variables within the template are identified by **$**, and the **substitute method** replaces them with actual values. This method is beneficial when handling user-generated or external data to prevent injection attacks. # Details on f-strings (Expressions) ![[zImagesCloud/details_f_strings.png]] ## Objective Use an f-string to write a diary entry that includes a mathematical expression evaluating the total cost of their dinner out. ## Dataset ```python meal_cost = round(random.uniform(20, 100), 2) tip_percent = random.choice([10, 15, 20]) total_cost = meal_cost * (1 + tip_percent / 100) entry = f"Dinner out cost us: ${total_cost:.2f} (including tip)." print(entry) ``` ## Solution ```python # Assuming variables meal_cost and tip_percent are defined total_cost = meal_cost * (1 + tip_percent / 100) entry = f"Dinner out cost us: ${total_cost:.2f} (including tip)." print(entry) ``` ## Explanation This solution demonstrates the power of f-strings for embedding expressions directly within the string. The expression calculates the total cost, including the tip, and formats it to two decimal places directly within the f-string. # Multi-line f-strings and Special Characters ![[zImagesCloud/multi_line_f_string.png]] ## Objective Create a multi-line diary entry describing a dream one of them had, using special characters for formatting. ## Dataset ```python dreamer = random.choice(['Husband', 'Wife']) dream_description = faker.text() entry = f""" {dreamer}'s Dream Diary: --------------------- {dream_description} --------------------- """ print(entry) ``` ## Solution ```python # Assuming variables dreamer and dream_description are defined entry = f""" {dreamer}'s Dream Diary: --------------------- {dream_description} --------------------- """ print(entry) ``` ## Explanation Multi-line f-strings allow for the creation of complex and formatted text blocks easily. Special characters like newlines **\n** and dashes for decoration are preserved in the output, making it suitable for entries that require a distinct visual format, such as a dream diary.