Welcome to our journey into Python strings! Today, we will delve into string operations, such as concatenation and slicing, and explore a variety of essential built-in string methods available in Python. By the end of your journey, you will have mastered these operations.
In Python, a String
is a sequence of characters. You can define them using single ('
), double ("
), or triple ('''
or """
) quotes for multiline strings:
Like lists, strings in Python have indices that start at 0.
Concatenation links strings together, much like joining links in a chain. Python uses the '+'
and '+='
operators for concatenation:
Note: The '+'
operator is used only to join strings.
Slicing in Python is akin to slicing a loaf of bread — you take a piece from the whole. The syntax is pretty simple: str[start:end]
that takes a slice from start
to end,
with start
inclusive and end
exclusive. For example:
Python is equipped with various string methods, such as:
str.upper()
- converts all string letters to uppercase.str.lower()
- converts all string letters to lowercase.str.replace(from, to)
- replaces all occurrences offrom
toto
.str.index(sub)
- searches the index of the first occurrence of the provided substringsub
.str.join(e1, e2, ...)
- joins all provided stringse1
,e2
, ... with a provided separatorstr
.str.split(separator)
- splits the provided string into multiple parts by the providedseparator
.len(str)
- returns the length of the stringstr
.str * <number>
- repeats thestr
multiple times (number
times).
Here's an example of how they work:
Python recognizes special escape sequences, such as \n
(newline), \t
(tab), and \\
(backslash). Here's a quick demonstration:
The message appears on two lines because \n
introduces a new line. \t
adds a tab space, and to print a single backslash, we use \\
.
Fantastic job! You've tackled Python string operations, learned about a variety of essential methods, and got acquainted with Python's special escape sequences. Practicing these will surely enhance your Python skills. Prepare for upcoming lessons on string formatting and interpolation. Onward!
