Strings
Creation
Creating a string in Python is done using single quotes ('...'
), double quotes ("..."
), or triple quotes ('''...'''
or """..."""
) for multi-line strings.
variable1 = 42 # creating an integer
print("Variable type:", type(variable1))
variable1 = "42" # creating a string
print("Variable type:", type(variable1))
Variable type: <class 'int'>
Variable type: <class 'str'>
Concatenation
It is possible to stick strings together using the +
operator, this is called concatenation.
animal = "cat"
name = "Felix"
sentence = "My animal is a "+animal+", and its name is "+name
sentence
which is equal to:
"My animal is a cat, and its name is Felix"String methods
Method | Description | Example |
---|---|---|
join() | Concatenates a sequence of elements into a single string, inserting a string between each element. | '/'.join(['monday', 'tuesday', 'wednesday']) returns 'monday/tuesday/wednesday' |
split() | Splits a string into a list of substrings. The default separator is space. | 'monday tuesday wednesday'.split() returns ['monday', 'tuesday', 'wednesday'] |
upper() | Transforms the string to uppercase. | 'inFoRmatics'.upper() returns 'INFORMATICS' |
lower() | Transforms the string to lowercase. | 'iNfOrMatics'.lower() returns 'informatics' |
capitalize() | Transforms the first character to uppercase and the rest to lowercase. | 'iNfOrMaticS'.capitalize() returns 'Informatics' |
replace() | Replaces a sequence of characters in a string with another. | 'Cats are independent.'.replace('Cats', 'Dogs') returns 'Dogs are independent.' |
Formatting
.format()
Method
We call the format()
method on a string. In this string, we identify the locations where we want to insert values using substitution markers {}
.
We then indicate as parameters of the format()
method the values we want to insert in place of the markers. Let's take the previous example with this principle:
animal = "cat"
name = "Felix"
sentence = "My animal is a {}, and its name is {}".format(animal, name)
sentence
which is equal to:
"My animal is a cat, and its name is Felix"Substitution markers can be completed with a key or index to facilitate formatting and organization of arguments:
animal = "cat"
name = "Felix"
sentence = "My animal is a {var1}, and its name is {firstname}".format(var1=animal, firstname=name)
sentence = "My animal is a {1}, and its name is {0}".format(name, animal)
f-strings
Since Python 3.6, we can format strings more easily using f-strings. Remember to add the letter f
before the quotes.
f-strings are more performant than the .format()
method, they are also more readable, making them a recommended practice for Python 3.6 and higher versions.
animal = "cat"
name = "Felix"
sentence = f"My animal is a {animal}, and its name is {name}"
The .format()
method like f-strings allow more advanced formatting, we will talk about it later.