python-for-j277 / getting-started · Lesson 03
Lesson 03 — Getting started
String Manipulation
Join, reshape and format text.
Text in Python is called a string. Here you will join strings together, reshape them, and learn two tidy ways to drop values into a sentence.
Joining strings (concatenation)
Joining strings with + is called concatenation.
first = "Ada"
last = "Lovelace"
full = first + " " + last
print(full)Output
Ada Lovelace
How it works
"Ada" + " " + "Lovelace"sticks the pieces together in order.- We add a
" "(a space) in the middle, otherwise we would get 'AdaLovelace'.
Text joins to text
+ only joins a string to another string. To join a number, cast it first with str(), for example "Score: " + str(10).Changing the case of text
word = "Python"
print(word.upper())
print(word.lower())
print(word.capitalize())Output
PYTHON python Python
How it works
.upper()returns the text in capitals..lower()returns it all in lower case..capitalize()makes just the first letter a capital and the rest lower case.- These are methods — actions that belong to a string and are written after a dot.
Methods make a copyThese methods return a new string; they do not change the original.
word is still "Python" afterwards.f-strings: the easy way to build a sentence
name = "Sam"
score = 8
print(f"Well done {name}, you scored {score} out of 10")Output
Well done Sam, you scored 8 out of 10
How it works
- Put the letter
fdirectly before the opening quote to make an f-string. - Anything inside
{curly brackets}is replaced by the value of that variable. - Numbers are handled for you — no casting needed.
The .format() method
name = "Sam"
score = 8
print("Well done {}, you scored {} out of 10".format(name, score))Output
Well done Sam, you scored 8 out of 10
How it works
- Each empty
{}is a placeholder. .format()fills the placeholders in order with the values you give it.- This does the same job as an f-string; f-strings are usually shorter and easier to read.
Two neat ways to build sentencesBoth f-strings and
.format() let you build a sentence from variables without lots of + signs.What you have learned
- Concatenation joins strings with
+; remember to add spaces yourself. .upper(),.lower()and.capitalize()return reshaped copies of a string.- Methods are written after a dot and return a new value.
f"...{variable}..."drops values straight into text."...{}...".format(value)fills placeholders in order.