Loops, and where your data lives

INPUT · Slides

Working on a string

01 / 07

Into capitals and into lower case

upper puts every letter into capitals; lower puts every letter into lower case.

The writing is what it has been all along: a . on the end of the string. Nothing goes in the brackets.

word = "python"print(word.upper())print("HELLO".lower())

Result

PYTHON
hello

02 / 07

The original does not change

This is the most important thing in the lesson. Calling upper does not change the variable.

Last lesson you learned that a string cannot be written over. So instead of altering the original, the tools for working on strings build a new one and hand it back.

word = "python"word.upper()print(word)

Result

python

03 / 07

Catch the result, or use it there and then

So how do you get at what came back? Two ways.

  • Put it back in the variable … word = word.upper()
  • Use it on the spot … print(word.upper())

Either is fine. What matters is that you take hold of what was handed back.

word = "python"word = word.upper()print(word)

Result

PYTHON

04 / 07

Shed the spaces at either end

strip takes off the spaces at both ends of a string.

Spaces in the middle stay where they are. The ends, and only the ends.

The example puts [ and ] round it so you can see how far the shedding went.

name = "  Grace  "print("[" + name + "]")print("[" + name.strip() + "]")

Result

[  Grace  ]
[Grace]

05 / 07

Swapping one thing for another

replace puts one string in place of another.

In the brackets you write what to look for and what to put there instead, in that order, separated by a comma.

weather = "rain then sun"print(weather.replace("rain", "cloud"))

Result

cloud then sun

06 / 07

replace swaps every one it finds

Not just the first one — all of them. Worth knowing.

Put "" (a string with nothing in it) as the replacement and you have a way of deleting instead.

weather = "rain then rain"print(weather.replace("rain", "snow"))print("020-7946-0123".replace("-", ""))

Result

snow then snow
02079460123

07 / 07

They chain together

Since what comes back is a string, you can put another . on that result and carry on.

strip and then replace, written in one go. The work happens left to right.

Next lesson has the tools for going between a string and a list. This feeling of "something new comes back" carries over there too.

text = "  rain  "print(text.strip().replace("rain", "sun"))

Result

sun