MPK23-Zwischenlager

Aus Attraktor Wiki

Wechseln zu: Navigation, Suche

Diese Seite dient zum Zwischenspeichern von Artikeln für den Micropythonkurs 2023

Für String Erweiterungen im Teil 2

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.

>>> txt1 = "My name is {fname}, I'm {age}".format(fname = "John", age = 36)
>>> txt2 = "My name is {0}, I'm {1}".format("John",36)
>>> txt3 = "My name is {}, I'm {}".format("John",36) 
>>> txt3 = "My name is {}, I'm {:5}".format("John",36) 
>>> txt3
"My name is John, I'm    36"
>>> txt3 = "My name is {}, I'm {:5.2}".format("John",36) 
>>> txt3
"My name is John, I'm    36"
>>> txt3 = "My name is {}, I'm {:5.2f}".format("John",36) 
>>> txt3
"My name is John, I'm 36.00"
>>> 

Slicing

The basics of slicing

My good friend John has a very long name:

John Alexander Harrington Fitzsimmons O'Leary Smith.

Quite a mouthful, hun?!

Well, let's put these names into a list:

>>> names = "John Alexander Harrington Fitzsimmons O'Leary Smith".split()
>>> names
['John', 'Alexander', 'Harrington', 'Fitzsimmons', "O'Leary", 'Smith']

Using indexing, we can easily access whichever single name we want.

For example, we can easily access John's first or last names:

>>> names[0]
'John'
>>> names[-1]
'Smith'

(If you didn't know you could use the index -1 to fetch the last element of a list, you must read this ASAP!)

Now, if you want to get the two first names, the four surnames, or the four middle names, you need to use sequence slicing.

By definition, “sequence slicing” is the means through which you can access multiple consecutive positions of a sequence, like a list.

Here is an example to extract John's two first names:

>>> names[0:2]
['John', 'Alexander']

Rumours say that's the code that governments all over the world use to generate the section “First names” for the passports and national identity cards of their citizens.

The example above shows that the square brackets [], that you also use for indexing, are used for slicing.

We typically think of the slicing integers in terms of [start : stop], because the first index tells Python where to start and the second one tells Python where to stop:

    start is the index of the first element to include in the result – names[0] is "John"
    stop is the index of the first element that is not included in the result – names[2] is "Harrington" but the last name in the result of names[0:2] was "Alexander"

This may look confusing at first, but this diagram should clear any doubts you might have and also provides a good mnemonic so you never forget how this works.

When the first integer of the slice is 0, it can be omitted.

This means that names[0:2] and names[:2] is equivalent.

Similarly, if you want the slice to go all the way to the end of the sequence, you can omit the stop index.

To give you an example of this, I'll tell you some inside information I got from a friend.

There are rumours that the function below is used by governments from all over the world to generate the section of “Surnames” on the passports of their citizens:

def surnames(names):
    return names[2:]

print(surnames(names))
# ['Harrington', 'Fitzsimmons', "O'Leary", 'Smith']

Slices are objects, too!

I had been using slicing for a long time when I learned something crazy about slicing.

Slices – the numbers you type separated by colons :, are actually Python objects!

You can create a slice and use it to perform slicing operations:

>>> names[slice(1, -1)]
['Alexander', 'Harrington', 'Fitzsimmons', "O'Leary"]

Isn't this surprising?!

It blew my mind when I found out for the first time.

But then again...

Everything in Python is an object, so maybe I shouldn't have been so surprised!

Now, if slices are objects, then you can name them too!

Here is a slice that drops the first element of any list:

>>> drop_first = slice(1, None)
>>> names[drop_first]
['Alexander', 'Harrington', 'Fitzsimmons', "O'Leary", 'Smith']
>>> ["first", "second", "third"][drop_first]
['second', 'third']

Take a moment to let that sink in!

With named slices, you could rewrite the government code we saw above:

>>> first_names = slice(None, 2)
>>> surnames = slice(2, None)
>>> names[first_names]
['John', 'Alexander']
>>> names[surnames]
['Harrington', 'Fitzsimmons', "O'Leary", 'Smith']

Named slices aren't seen very often in the wild because most programmers just learn about the sequence slicing idioms.

However, I find that slicing is the perfect example of what “everything in Python is an object” means.

If this piqued your interest, I've written about the inner workings of sequence slicing on my blog, so feel free to take a look!

Finally, I need to disclose that this email essentially copied the subject that my good friend Stephen wrote about very recently.

When I saw Stephen's email I jumped on my seat because I really like the fact that you can name slices.

So, thank you, Stephen!

By the way, you can also influence what I write about.

If there is something you'd like me to write about, reply to this email and I'll see what I can do.
ICYMI

In Case You Missed It, over the past few days I rewrote an article I have about about list comprehensions 101.

Now it has better examples, better diagrams, and some nice animations that show how everything works.

​Take a look and let me know if you have any suggestions for improvements.