15. Lektion: Stringbearbeitung: Difference between revisions
| Line 105: | Line 105: | ||
===== Erweiterte Formatanweisungen===== | ===== Erweiterte Formatanweisungen===== | ||
https://www.w3schools.com/python/ref_string_format.asp<br> | https://www.w3schools.com/python/ref_string_format.asp<br> | ||
Es gibt weitere Möglichkeiten die eingefügten Werte zu formatieren. | Es gibt weitere Möglichkeiten die eingefügten Werte zu formatieren.<br> | ||
Dazu werden Formatierungsanweisungen in die {} eingetragen.<br> | |||
Diese Anweisungen werden mit einem : eingeleitet<br> | |||
Z.B: | |||
<pre> | <pre> | ||
>>> 'Hallo, {:5s} Hallo.'.format('a') | >>> 'Hallo, {:5s} Hallo.'.format('a') | ||
| Line 112: | Line 114: | ||
>>> 'Hallo, {:>5s} Hallo.'.format('a') | >>> 'Hallo, {:>5s} Hallo.'.format('a') | ||
'Hallo, a Hallo.' | 'Hallo, a Hallo.' | ||
>>> | >>> 'Der Wert ist {:5.2f}'.format(3.1456) | ||
'Der Wert ist 3.15' | |||
</pre> | </pre> | ||
Revision as of 21:21, 27 September 2023
String Methoden
Die Klasse String enthält eine ganze Reihe von Methoden die einen komfortablen Umgang mit Strings ermöglichen. Der Umfang an Methoden ist bei Micropython reduziert.
>>> dir(str) ['__class__', '__name__', 'count', 'endswith', 'find', 'format', 'index', 'isalpha', 'isdigit', 'islower', 'isspace', 'isupper', 'join', 'lower', 'lstrip', 'replace', 'rfind', 'rindex', 'rsplit', 'rstrip', 'split', 'startswith', 'strip', 'upper', '__bases__', '__dict__', 'center', 'encode', 'partition', 'rpartition', 'splitlines'] >>>
Groß- und Kleinschreibung
Zum Umwandelt von Texten in Groß- oder Kleinschreibung gibt es die Methoden upper() und lower():
>>> hallo = 'Hallo'
>>> hallo_klein = hallo.lower()
>>> hallo_klein
'hallo'
>>> hallo_gross = hallo.upper()
>>> hallo_gross
'HALLO'
>>>
Es läßt sich auch prüfen, ob ein Text groß oder klein geschrieben ist. Wenn sowohl Groß- als auch Kleinbuchstaben enthalten sind werden beide Abfragen False.
>>> text = 'Hallo'
>>> text.isupper()
False
>>> text.islower()
False
>>> text.lower().islower()
True
>>> text.upper().islower()
False
>>>
Von Whitespaces befreien
Mit strip kann man Whitespaces aus Strings entfernen.
>>> text_form = ' Hallo ' >>> text_form ' Hallo ' >>> text_form.strip() 'Hallo' >>> text_form.lstrip() 'Hallo ' >>> text_form.rstrip() ' Hallo' >>>
Texte ausrichten
Zum Ausrichten von Texten steht in Micropython nur die center-Methode zur Verfügung. Als Parameter wird die Größe des Feldes angegeben in dem der Text zentriert werden soll.
>>> text = 'Hallo' >>> text.center(20) ' Hallo '
Sätze in Worte zerteilen
Mit split lässt sich ein Satz in seine einzelnen Wörter zerteilen. Dabei entsteht eine Liste.
>>> text = 'Hallo, Micropython ist ganz toll!' >>> text.split() ['Hallo,', 'Micropython', 'ist', 'ganz', 'toll!'] >>>
Sätze aus Worten zusammensetzen
Mit join kann aus einer Liste von Worten ein Satz zusammengesetzt werden. Als Ausgangsstring wird das Trennzeichen zwischen den Worten verwendet.
>>> ' '.join(wort_liste)
'Hallo, Micropython ist ganz toll!'
>>>
Praktisch ist es auch bei Zeitangaben:
>>> stunde = '7'
>>> minute = '25'
>>> sekunde = '38'
>>> ':'.join([stunde, minute, sekunde])
'7:25:38'
>>>
Texte mit Werten auffüllen
Formatierung
Es gibt in Python 3 Arten Texte zu formatieren. In diesem Fall bedeutet das, Einfügen von Werten in einen bestehenden Text. Davon stehen in Micropython nur die 2 älteren Methoden zur Verfügung. Die neueste, f-Formatierung genannt, gibt es in Micropython noch nicht. Bei Internetsuchen zur Formatierung in Python stößt man inzwischen meist auf die f-Formatierung. Das ist für Micropython wenig hilfreich. Deshalb ist es sinnvoller nach %-Formatierung oder .format() zu suchen.
%-Formatierung
Dieses ist die älteste Formatierung von Python. Deshalb werde ich darauf nicht weiter eingehen,
.format()-Formatierung
Bei dieser Art der Formatierung wird als Platzhalter im Text {} eingesetzt. .format() ist eine Methode der Klasse string. Die einzusetzten Werte werden in der richtigen Reihenfolge als Parameter übergeben.
>>> text = 'Hallo {}, schön das Du da bist'.format('Peter')
>>> text
'Hallo Peter, sch\xf6n das Du da bist'
>>> print(text)
Hallo Peter, schön das Du da bist
>>>
Erweiterte Formatanweisungen
https://www.w3schools.com/python/ref_string_format.asp
Es gibt weitere Möglichkeiten die eingefügten Werte zu formatieren.
Dazu werden Formatierungsanweisungen in die {} eingetragen.
Diese Anweisungen werden mit einem : eingeleitet
Z.B:
>>> 'Hallo, {:5s} Hallo.'.format('a')
'Hallo, a Hallo.'
>>> 'Hallo, {:>5s} Hallo.'.format('a')
'Hallo, a Hallo.'
>>> 'Der Wert ist {:5.2f}'.format(3.1456)
'Der Wert ist 3.15'
:< Left aligns the result (within the available space) :> Right aligns the result (within the available space) :^ Center aligns the result (within the available space) := Places the sign to the left most position :+ Use a plus sign to indicate if the result is positive or negative :- Use a minus sign for negative values only : Use a space to insert an extra space before positive numbers (and a minus sign before negative numbers) :, Use a comma as a thousand separator :_ Use a underscore as a thousand separator :b Binary format :c Converts the value into the corresponding unicode character :d Decimal format :e Scientific format, with a lower case e :E Scientific format, with an upper case E :f Fix point number format :F Fix point number format, in uppercase format (show inf and nan as INF and NAN) :g General format :G General format (using a upper case E for scientific notations) :o Octal format :x Hex format, lower case :X Hex format, upper case :n Number format :% Percentage format
- https://en.wikipedia.org/wiki/ASCII
- https://nedbatchelder.com/text/unipain.html
- https://docs.microphyton.org/en/v1.12/genrst/builtin_types.html?highlight=ljust
- https://www.phyton-lernen.de/string-methode-center.htm
- https://en.wikipedia.org/wiki/ASCII
- https://nedbatchelder.com/text/unipain.html
- https://medium.com/@sami.hamdiapps/elevate-your-python-skills-string-comparison-python-made-easy-bd0b3b08b55b
- https://levelup.gitconnected.com/10-more-python-methods-for-manipulating-strings-545f73211d37
- .format und %
- input()
Zurück zu Micropython Kurs 2023 - Teil 1
Zurück zur "Micropython Kurs 2023" Startseite
Zurück zur Programmieren Startseite
Zurück zur Wiki Startseite