Direkt zum Inhalt

Aktualisierte 13. Feb. 2025  · 10 Min. Lesezeit

# Define variables
name = 'Mark'
profession = 'Astronaut'
age = 7


# Output info
output_string = ('My name is ' + name +
                ', I am ' + str(age) + ' years old ' +
                'and my profession is ' + profession + '.')
print(output_string)
   My name is Mark, I am 7 years old and my profession is Astronaut.

# Define variables
name = 'Mark'
profession = 'Astronaut'
age = 7


# Output info
output_string = f'My name is {name}, I am {age} years old and my profession is {profession}.'
print(output_string)
   My name is Mark, I am 7 years old and my profession is Astronaut.

name = 'Mark'
output_string = f'My name is {name}.'
print(output_string)
   My name is Mark.

import math


a = 3.0
b = 4.0


# Use string interpolation for the formula
print(f'The hypotenuse of a triangle with base {a} and side {b} is {math.sqrt(a ** 2 + b ** 2)}.')
   The hypotenuse of a triangle with base 3.0 and side 4.0 is 5.0.

name = 'Mark'
output_string = 'My name is {}.'.format(name)
print(output_string)
   My name is Mark.

name = 'Mark'
age = 7


# The placeholders are filled in order of the arguments
output_string = 'My name is {} and I am {} years old.'.format(name, age)


print(output_string)
   My name is Mark and I am 7 years old.

name = 'Mark'
age = 7


# Print age twice
output_string = 'My name is {} and I am {} years old. My twin brother is also {} years old.'.format(name, age, age)
print(output_string)
   My name is Mark and I am 7 years old. My twin brother is also 7 years old.

name = 'Mark'
age = 7


# Use indexed placeholders
output_string = 'My name is {0} and I am {1} years old. My twin brother is also {1} years old.'.format(name, age)
print(output_string)
   My name is Mark and I am 7 years old. My twin brother is also 7 years old.

print('My name is {name} and I am {age} years old.'.format(name='Mark', age=7))
   My name is Mark and I am 7 years old.

'Hello %s' % 'Mark'
   'Hello Mark'

%s

%d

25"

%f

"Pi: %f" % 3.14159 → "Pi: 3.141590"

%.nf

%x

%X

"%X" % 255 → "FF"

%o

name = "Alice"
age = 30
height = 5.6


# The % operator is hard to scan
message = "My name is %s, I am %d years old, and my height is %.1f feet." % (name, age, height)
print(message)
   My name is Alice, I am 30 years old, and my height is 5.6 feet.

# This is much cleaner
message = f"My name is {name}, I am {age} years old, and my height is {height:.1f} feet."
print(message)
   My name is Alice, I am 30 years old, and my height is 5.6 feet.

 

name = 'Mark'
profession = 'Astronaut'
age = 7


# This is an example of a multiline string
bio = f"""
Name: {name}
Profession: {profession}
Age: {age}
"""
print(bio)
   Name: Mark

   Profession: Astronaut

   Age: 7
name = 'Mark'
profession = 'Astronaut'
age = 7


# This is a multiline string with .format()
bio = """
Name: {}
Profession: {}
Age: {}
""".format(name, profession, age)
print(bio)
   Name: Mark

   Profession: Astronaut

   Age: 7

name = "Alice"
event = "Annual Tech Conference"
date = "March 15, 2025"


email = """Dear {name},


We are pleased to invite you to the {event} taking place on {date}.
We hope you can join us for an exciting experience.


Best regards, 
The Event Team""".format(name=name, event=event, date=date)


print(email)
   Dear Alice,

  

   We are pleased to invite you to the Annual Tech Conference taking place on March 15, 2025.

   We hope you can join us for an exciting experience.

  

   Best regards, 

   The Event Team

error_code = 404
url = '/missing-page'
timestamp = '2025-02-05 12:30:00'
error_message = 'The requested page could not be found.'


log_message = f"""[ERROR {error_code}]
Time: {timestamp}
URL: {url}


{error_message}"""


print(log_message)
   [ERROR 404]

   Time: 2025-02-05 12:30:00

   URL: /missing-page

 

   The requested page could not be found.

table = 'users'
column = 'email'
value = 'alice@example.com'


query = f"""SELECT *
FROM {table}
WHERE {column} = '{value}';"""


print(query)
   SELECT *

   FROM users

   WHERE email = 'alice@example.com';

pi = 3.1415926535


print(f'Pi rounded to 2 decimal places: {pi:.2f}')
print(f'Pi rounded to 4 decimal places: {pi:.4f}')
print(f'Pi rounded to 0 decimal places: {pi:.0f}')
   Pi rounded to 2 decimal places: 3.14
   Pi rounded to 4 decimal places: 3.1416
   Pi rounded to 0 decimal places: 3
print('Pi rounded to 2 decimal places: {:.2f}'.format(pi))
print('Pi rounded to 4 decimal places: {:.4f}'.format(pi))
print('Pi rounded to 0 decimal places: {:.0f}'.format(pi))
   Pi rounded to 2 decimal places: 3.14
   Pi rounded to 4 decimal places: 3.1416
   Pi rounded to 0 decimal places: 3
score = 0.875
print(f"Success rate: {score:.2%}")
   Success rate: 87.50%

amount = 98765.4321


print(f"USD: ${amount:,.2f}")
print(f"EUR: €{amount:,.2f}")
print(f"GBP: £{amount:,.2f}")
   USD: $98,765.43

   EUR: €98,765.43

   GBP: £98,765.43

person = {
   'name': 'Alice',
   'age': 30,
   'city': 'New York'
}


print(f"My name is {person['name']}, I am {person['age']} years old, and I live in {person['city']}.")
   My name is Alice, I am 30 years old, and I live in New York.
person = {
   'name': 'Alice',
   'age': 30,
}


print(f'My name is {name} and I am {age} years old.'.format(**person))
   My name is Alice and I am 7 years old.
person = {"name": "Alice"}


# Error: key 'city' is missing
print(f"City: {person['city']}") 
   ---------------------------------------------------------------------------




   KeyError                                  Traceback (most recent call last)




   Cell In[87], line 4

         1 person = {"name": "Alice"}

         3 # Error: key 'city' is missing

   ----> 4 print(f"City: {person['city']}")







   KeyError: 'city'
print(f"City: {person.get('city', 'Not specified')}")
   City: Not specified

.format()

🟡 OK

print('Hello, my name is {name!'}
     Cell In[96], line 1

       print('Hello, my name is {name!'}
                                       ^
   SyntaxError: closing parenthesis '}' does not match opening parenthesis '('

print(f'Set notation: {a, b, c}')
   ---------------------------------------------------------------------------

   NameError                                 Traceback (most recent call last)

   Cell In[101], line 1

   ----> 1 print(f'Set notation: {a, b, c}')

   NameError: name 'c' is not defined

print("Set notation: {{a, b, c}}")

   

import timeit


name = "Alice"
age = 30
pi = 3.1415926535


# Measure f-string performance
f_string_time = timeit.timeit('f"My name is {name} and I am {age} years old."', globals=globals(), number=1000000)


# Measure .format() performance
format_time = timeit.timeit('"My name is {} and I am {} years old.".format(name, age)', globals=globals(), number=1000000)


# Measure f-string performance with expressions
f_string_expr_time = timeit.timeit('f"Pi rounded to 2 decimal places: {pi:.2f}"', globals=globals(), number=1000000)


# Measure .format() performance with expressions
format_expr_time = timeit.timeit('"Pi rounded to 2 decimal places: {:.2f}".format(pi)', globals=globals(), number=1000000)


# Print results
print(f"f-string (simple): {f_string_time:.6f} seconds")
print(f".format() (simple): {format_time:.6f} seconds")
print(f"f-string (with expression): {f_string_expr_time:.6f} seconds")
print(f".format() (with expression): {format_expr_time:.6f} seconds")
   f-string (simple): 0.080447 seconds

   .format() (simple): 0.129860 seconds

   f-string (with expression): 0.123171 seconds

   .format() (with expression): 0.146242 seconds

# Recommended
name = "Alice"
age = 30
print(f"My name is {name} and I am {age} years old.")


# Not Recommended (Less readable)
print("My name is {} and I am {} years old.".format(name, age))


# Avoid using % formatting (Outdated)
print("My name is %s and I am %d years old." % (name, age))
   My name is Alice and I am 30 years old.

   My name is Alice and I am 30 years old.

   My name is Alice and I am 30 years old.
# Named placeholders (readable)
user = {"name": "Alice", "age": 30}
print(f"My name is {user['name']} and I am {user['age']} years old.")


# Using indexes in .format() (not as readable)
print("My name is {0} and I am {1} years old.".format("Alice", 30))
   My name is Alice and I am 30 years old.

   My name is Alice and I am 30 years old.
name = "Alice"
age = 30


message = f"""Hello, {name}!


We are happy to invite you to our event.
At {age} years old, you are eligible for the VIP pass.


Best regards,
Event Team
"""
print(message)
   Hello, Alice!


   We are happy to invite you to our event.

   At 30 years old, you are eligible for the VIP pass.


   Best regards,

   Event Team  
value = 42


# Output: value = 42
print(f"{value = }") 
   value = 42

Python von Grund auf lernen

Beherrsche Python für Data Science und erwerbe gefragte Fähigkeiten.
Kostenloses Lernen beginnen

user = {"name": "Alice", "age": 30}
print(f"My name is {user['name']} and I am {user['age']} years old.")
print(f"My name is {name} and I am {age}.".format(**user))

pi = 3.14159
print(f"Pi: {pi:.2f}")

Mark Pedigo's photo
Author
Mark Pedigo
LinkedIn

Mark Pedigo, PhD, ist ein angesehener Datenwissenschaftler mit Fachwissen in den Bereichen Datenwissenschaft im Gesundheitswesen, Programmierung und Bildung. Mit einem Doktortitel in Mathematik, einem B.S. in Informatik und einem Professional Certificate in KI verbindet Mark technisches Wissen mit praktischer Problemlösungskompetenz. In seiner beruflichen Laufbahn war er unter anderem an der Aufdeckung von Betrug, der Vorhersage von Kindersterblichkeit und Finanzprognosen beteiligt und hat an der Kostenschätzungssoftware der NASA mitgearbeitet. Als Pädagoge hat er auf dem DataCamp und an der Washington University in St. Louis unterrichtet und junge Programmierer angeleitet. In seiner Freizeit genießt Mark mit seiner Frau Mandy und seinem Hund Harley die Natur in Minnesota und spielt Jazz-Piano.

Themen

Lernpfad

hr
Siehe DetailsRight Arrow
Kurs starten
Zertifizierung verfügbar

Kurs

4 hr
6M
Mehr anzeigenRight Arrow