In diesem Schritt lernen Sie verschiedene Möglichkeiten kennen, Strings in Python zu formatieren, was für die Erstellung lesbarer und gut strukturierter Ausgaben unerlässlich ist.
Während die String-Verkettung mit dem +
-Operator funktioniert, kann sie umständlich werden, insbesondere wenn Strings mit anderen Datentypen wie Zahlen kombiniert werden.
Erstellen Sie eine neue Datei namens string_formatting.py
im Verzeichnis ~/project
.
## string_formatting.py
## Verkettung mit Typumwandlung
print('This year is ' + str(2021) + ' year')
## Dies würde einen Fehler verursachen:
## print('This year is ' + 2021 + ' year')
Speichern Sie die Datei und führen Sie sie aus:
python ~/project/string_formatting.py
This year is 2021 year
Python bietet elegantere Möglichkeiten zur Formatierung von Strings.
f-Strings (formatierte String-Literale) wurden in Python 3.6 eingeführt und bieten eine prägnante Möglichkeit, Ausdrücke in String-Literale einzubetten. Sie stellen dem String ein f
oder F
voran und platzieren Ausdrücke in geschweiften Klammern {}
.
Fügen Sie den folgenden Code zu string_formatting.py
hinzu:
## string_formatting.py
## Verkettung mit Typumwandlung
print('This year is ' + str(2021) + ' year')
## f-string grundlegende Verwendung
year = 2021
month = 4
day = 1
print(f"Today is {year} year {month} month {day} day")
Speichern und ausführen:
python ~/project/string_formatting.py
This year is 2021 year
Today is 2021 year 4 month 1 day
Sie können optionale Format-Spezifizierer nach einem Doppelpunkt (:
) innerhalb der geschweiften Klammern verwenden, um die Formatierung des eingebetteten Ausdrucks zu steuern.
Fügen Sie weitere f-String-Beispiele mit Format-Spezifizierern hinzu:
## string_formatting.py
## Verkettung mit Typumwandlung
print('This year is ' + str(2021) + ' year')
## f-string grundlegende Verwendung
year = 2021
month = 4
day = 1
print(f"Today is {year} year {month} month {day} day")
## Format-Spezifizierer
pi = 3.1415926
print(f'Pi gerundet auf zwei Dezimalstellen ist: {pi:.2f}') ## Präzision angeben
print(f'Pi mit Standardpräzision ist: {pi:f}') ## Standardpräzision
## Feldbreite und Ausrichtung
name1 = 'Bob'
age1 = 20
name2 = 'John'
age2 = 25
print(f'{name1:6}=>{age1:6}\n{name2:6}=>{age2:6}')
## Nullauffüllung
total = 2000
print(f'Gesamtbetrag: {total:08} Yuan')
## Tausendertrennzeichen
print(f'{100000000000}')
print(f'{100000000000:_}')
print(f'{100000000000:,}')
## Zahlenbasis-Trennzeichen
print(f'{0b10000000:_b}') ## Binär-Trennzeichen
print(f'{128:_b}') ## Dezimal zu Binär mit Trennzeichen
print(f'{10000:_o}') ## Dezimal zu Oktal mit Trennzeichen
print(f'{12800000:_x}') ## Dezimal zu Hexadezimal mit Trennzeichen
## Prozentformatierung
print(f'{0.25:%}') ## Standardpräzision
print(f'{0.25:.2%}') ## Präzision angeben
## Andere Modifikatoren (!a, !s, !r)
name = 'Alice'
print(f'{name!a}')
print(f'{name!s}')
print(f'{name!r}')
## Datums-/Zeitformatierung
import datetime
d = datetime.datetime(2021, 10, 1, 8, 15, 58)
print(f'{d:%Y-%m-%d %H:%M:%S}')
Speichern und ausführen:
python ~/project/string_formatting.py
This year is 2021 year
Today is 2021 year 4 month 1 day
Pi rounded to two decimal places is: 3.14
Pi with default precision is: 3.141593
Bob => 20
John => 25
Total amount: 00002000 Yuan
100000000000
100_000_000_000
100,000,000,000
1000_0000
1000_0000
23420
c35000
25.000000%
25.00%
'Alice'
Alice
'Alice'
2021-10-01 08:15:58
Die Methode str.format()
ist eine weitere Möglichkeit, Strings zu formatieren. Sie verwenden geschweifte Klammern {}
als Platzhalter und übergeben die einzufügenden Werte als Argumente an die format()
-Methode.
Fügen Sie Beispiele mit der format()
-Methode hinzu:
## string_formatting.py
## ... (vorheriger Code) ...
## format() Methode - Positionsargumente
print('We are the {} who say "{}!"'.format('knights', 'Ni'))
print('{0} and {1}'.format('spam', 'eggs'))
print('{1} and {0}'.format('spam', 'eggs'))
## format() Methode - Schlüsselwortargumente
print('He is {age} years old and works in {city}.'.format(age=25, city='Beijing'))
## format() Methode - Format-Spezifizierer (ähnlich wie f-Strings)
pi = 3.1415926
print('Pi gerundet auf zwei Dezimalstellen ist: {:.2f}'.format(pi))
## Datums-/Zeitformatierung mit format()
import datetime
d = datetime.datetime(2021, 10, 1, 8, 15, 58)
print('{:%Y-%m-%d %H:%M:%S}'.format(d))
Speichern und ausführen:
python ~/project/string_formatting.py
This year is 2021 year
Today is 2021 year 4 month 1 day
Pi rounded to two decimal places is: 3.14
Pi with default precision is: 3.141593
Bob => 20
John => 25
Total amount: 00002000 Yuan
100000000000
100_000_000_000
100,000,000,000
1000_0000
1000_0000
23420
c35000
25.000000%
25.00%
'Alice'
Alice
'Alice'
2021-10-01 08:15:58
We are the knights who say "Ni!"
spam and eggs
eggs and spam
He is 25 years old and works in Beijing.
Pi rounded to two decimal places is: 3.14
2021-10-01 08:15:58
Der %
-Operator kann auch für die String-Formatierung verwendet werden, ist aber älter und aufgrund einiger Eigenheiten weniger empfehlenswert. Wir zeigen nur ein kurzes Beispiel.
Fügen Sie Folgendes zu string_formatting.py
hinzu:
## string_formatting.py
## ... (vorheriger Code) ...
## %-Formatierung (Legacy)
print('%s %s'%('Hello','World'))
print('Pi rounded to two decimal places is: %.2f'%(3.1415926))
Speichern und ausführen:
python ~/project/string_formatting.py
This year is 2021 year
Today is 2021 year 4 month 1 day
Pi rounded to two decimal places is: 3.14
Pi with default precision is: 3.141593
Bob => 20
John => 25
Total amount: 00002000 Yuan
100000000000
100_000_000_000
100,000,000,000
1000_0000
1000_0000
23420
c35000
25.000000%
25.00%
'Alice'
Alice
'Alice'
2021-10-01 08:15:58
We are the knights who say "Ni!"
spam and eggs
eggs and spam
He is 25 years old and works in Beijing.
Pi rounded to two decimal places is: 3.14
2021-10-01 08:15:58
Hello World
Pi rounded to two decimal places is: 3.14
Dreifache Anführungszeichen
Strings, die in dreifache Anführungszeichen ('''...'''
oder """..."""
) eingeschlossen sind, können sich über mehrere Zeilen erstrecken und alle Leerzeichen darin enthalten. Dies ist nützlich, um mehrzeilige Strings zu erstellen oder die Formatierung beizubehalten.
Fügen Sie ein Beispiel für einen String mit dreifachen Anführungszeichen hinzu:
## string_formatting.py
## ... (vorheriger Code) ...
## Dreifache Anführungszeichen
print('''\
===========Strings===========
Triple-quoted strings preserve whitespace,
allowing for formatted output.
''')
Speichern und ausführen:
python ~/project/string_formatting.py
This year is 2021 year
Today is 2021 year 4 month 1 day
Pi rounded to two decimal places is: 3.14
Pi with default precision is: 3.141593
Bob => 20
John => 25
Total amount: 00002000 Yuan
100000000000
100_000_000_000
100,000,000,000
1000_0000
1000_0000
23420
c35000
25.000000%
25.00%
'Alice'
Alice
'Alice'
2021-10-01 08:15:58
We are the knights who say "Ni!"
spam and eggs
eggs and spam
He is 25 years old and works in Beijing.
Pi rounded to two decimal places is: 3.14
2021-10-01 08:15:58
Hello World
Pi rounded to two decimal places is: 3.14
===========Strings===========
Triple-quoted strings preserve whitespace,
allowing for formatted output.