Working with strings
โ Report an issue with this lessonStrings support a lot of built-in operations. Concatenation:
first = "Ada"
last = "Lovelace"
full = first + " " + last
print(full) # Ada Lovelace
But the tool you'll reach for constantly is an f-string, which lets you embed variables directly inside text:
age = 28
print(f"{full} is {age} years old")
# Ada Lovelace is 28 years old
Useful string methods:
"Hello".lower() # 'hello'
"Hello".upper() # 'HELLO'
" hi ".strip() # 'hi'
"a,b,c".split(",") # ['a', 'b', 'c']
len("Hello") # 5
Strings are indexed starting at 0, and you can slice them:
word = "Python"
word[0] # 'P'
word[0:3] # 'Pyt'
word[-1] # 'n' (last character)
word[::-1] # 'nohtyP' -- a step of -1 reverses the string
Strings are immutable
You can't change a character in place -- word[0] = "J"
raises a TypeError. Every string method that looks like it
"changes" a string (.upper(), .replace(),
.strip()) actually returns a brand-new string and leaves the
original untouched:
text = "hello"
text.upper()
print(text) # still "hello" -- upper() didn't change it in place
text = text.upper() # you have to reassign to keep the result
print(text) # "HELLO"
This trips up a lot of beginners: calling a string method and expecting the original variable to have changed, then being confused when it hasn't.
More string methods worth knowing
"hello world".title() # 'Hello World'
"hello world".replace("world", "there") # 'hello there'
"hello".startswith("he") # True
"hello".endswith("lo") # True
"hello".find("l") # 2 -- index of first match, -1 if not found
",".join(["a", "b", "c"]) # 'a,b,c'
join is the reverse of split -- it's a method
on the separator string, which surprises people the first time
they see it, since you might expect it to be a method on the list instead.
Formatting numbers inside f-strings
price = 19.999
print(f"${price:.2f}") # $20.00 -- round to 2 decimal places
count = 7
print(f"{count:03}") # 007 -- pad with zeros to width 3
The part after the colon inside {} is a format spec --
.2f means "fixed-point, 2 decimal places," and it's the
standard way to control how numbers display without manually rounding or
padding them yourself.
Comparing f-strings to .format() and %
You may see two older styles in existing code:
"{} is {}".format(name, age) and
"%s is %s" % (name, age). Both still work, but f-strings are
the current standard -- they're shorter and let you see the variable name
directly inside the string instead of matching up positions by hand.
Try it yourself
HELLO WORLD FROM PYTHON ['hello', 'world', 'from', 'python']
Run your code and get it working before marking this lesson complete.
11 more lessons โ including Project: build a to-do list program โ plus a certificate are waiting.
Unlock the full course โ $29.99