15. Lektion: Stringbearbeitung: Unterschied zwischen den Versionen

Aus Attraktor Wiki

Wechseln zu: Navigation, Suche
(Texte mit Werten auffüllen)
(Erweiterte Formatanweisungen)
Zeile 108: Zeile 108:
  
 
<pre>
 
<pre>
 +
>>> 'Hallo, {:5s} Hallo.'.format('a')
 +
    'Hallo, a    Hallo.'
 +
>>> 'Hallo, {:>5s} Hallo.'.format('a')
 +
    'Hallo,    a Hallo.'
 +
>>>
 +
</pre>
  
 +
<pre>
 +
:< 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
 
</pre>
 
</pre>
 
 
  
 
** https://en.wikipedia.org/wiki/ASCII
 
** https://en.wikipedia.org/wiki/ASCII

Version vom 27. September 2023, 20:14 Uhr

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.

>>> 'Hallo, {:5s} Hallo.'.format('a')
    'Hallo, a     Hallo.'
>>> 'Hallo, {:>5s} Hallo.'.format('a')
    'Hallo,     a Hallo.'
>>> 
:< 	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

Navigation

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