So far, we've been using the + operator for combining string literals with the results of expressions.
artist = "Lil Nas X"
song = "Industry Baby"
place = 2
print("Debuting at #" + str(place) + ": '" + song + "' by " + artist)
But that's not ideal:
str()
ing non-strings
String interpolation is the process of combining string literals with the results of expressions.
Available since Python 3.5, f strings (formatted string literals) are the best way to do string interpolation.
Just put an f
in front of the quotes and then
put any valid Python expression in curly brackets inside:
artist = "Lil Nas X"
song = "Industry Baby"
place = 2
print(f"Debuting at #{place}: '{song}' by {artist}")
๐๐๐๐๐๐
Strings and lists are both considered sequences in Python.
so both support standard sequence operations,
like +
, *
, in
, and bracket notation.
title = 'The Parable of the Sower'
author = 'Octavia E. Butler'
full = title + ' By ' + author
contains_parable = 'Parable' in title
chant = 'We want more ' + (author + ',') * 3 + '!'
initials = author[0] + author[8] + author[11]
title_length = len(title)
However: strings are immutable.
Once created, they can't be changed.
Bracket notation can be used to either access individual characters or to make "slices".
adjective = 'superduper'
adjective[0] # 's'
adjective[-1] # 'r'
adjective[0:5] # 'super'
adjective[5:] # 'duper'
illness = 'pneumonoultramicroscopicsilicovolcanoconiosis'
true_start_sound = illness[1]
how_small = illness[13:24]
from_where = illness[30:37]
The string split()
method turns a string into a list of strings,
by splitting at the specified delimiter.
my_groceries = 'apples,bananas,carrots'
grocery_items = my_groceries.split(',')
for item in grocery_items:
print(item)
The string join()
method
returns a string which is the concatenation of the strings in an iterable.
names = ["Gray", "Fox"]
print("".join(names))
address_parts = ["123 Pining St", "Nibbsville", "OH"]
print(",".join(address_parts))
poem_lines = ["Forgive me", "they were delicious", "so sweet", "and so cold"]
print("\n".join(poem_lines))
Python offers many string methods. A few more:
Method | Description |
---|---|
str.replace(old, new)
| Returns a new string where occurrences of old are replaced with new .
|
str.find(substring)
| Returns the lowest index in the string where substring is found.
|
str.startswith(prefix)
| Returns True if the string starts with the prefix , and False otherwise.
|
str.endswith(suffix)
| Returns True if the strings ends with the prefix , and False otherwise.
|
str.strip([chars])
| Returns a copy of the string with leading and trailing characters removed, defaulting to whitespace characters. |
str.lower()
| Returns a copy of the string with all characters converted to lowercase. |
A dict
is a mutable mapping of key-value pairs
states = {
"CA": "California",
"DE": "Delaware",
"NY": "New York",
"TX": "Texas",
"WY": "Wyoming"
}
Queries:
>>> len(states)
5
>>> "CA" in states
True
>>> "ZZ" in states
False
words = {
"mรกs": "more",
"otro": "other",
"agua": "water"
}
Select a value:
>>> words["otro"]
'other'
>>> first_word = "agua"
>>> words[first_word]
'water'
>>> words["pavo"]
KeyError: pavo
>>> words.get("pavo", "๐ค")
'๐ค'
Create an empty dict:
users = {}
Add values:
users["profpamela"] = "b3stp@ssEvErDontHackMe"
Change values:
users["profpamela"] += "itsLongerSoItsMoreSecure!!"
>>> users["profpamela"]
'b3stp@ssEvErDontHackMeitsLongerSoItsMoreSecure!!'
spiders = {
"smeringopus": {
"name": "Pale Daddy Long-leg",
"length": 7
},
"holocnemus pluchei": {
"name": "Marbled cellar spider",
"length": (5, 7)
}
}
insects = {"spiders": 8, "centipedes": 100, "bees": 6}
for name in insects:
print(insects[name])
...is the same as:
for name in list(insects):
print(insects[name])
What will be the order of items?
8 100 6
Keys are iterated over in the order they are first added.