Strings (Advanced)
There are many useful things that you can do with strings.
String Slicing
Similar to lists, you can also pick out individual characters from a string.
The first letter has index 0, the second has index 1, and so on.
"Hello, World!"[0] # "H"
"Hello, World!"[1] # "e"
Keep in mind that spaces in strings also count as characters!
"Hello, World!"[6] # " "
Combing Strings
If you want to combine two strings together (called concatenation), you can use the +
operator.
"Hello" + " " + "World" # "Hello World"
Built-in string functions
Python comes with many built-in functions to help you format strings. These include:
.format()
.format
is a powerful string formatting function. It is very useful for creating dynamic strings.
It replaces the first {}
with the first word, the second {}
with the second word, and so on.
"{} {}".format("Hello", "World") # Hello World
.split()
.split
is a useful function for splitting strings into individual words.
"Hello World".split() # ["Hello", "World"]
You can also split them into characters.
"Apple".split("") # ["A", "p", "p", "l", "e"]
.strip()
.strip
is a useful function for removing leading and trailing whitespace.
" Hello World ".strip() # "Hello World"
.upper()
.upper
is a useful function for converting an entire string to uppercase.
"hello world".upper() # HELLO WORLD
.lower()
.lower
is a useful function for converting an entire string to lowercase.
"HELLO WORLD".lower() # hello world
.title()
.title
is a useful function for capitalizing the first letter of each word in a string.
"hello world".title() # Hello World