3 min read•june 24, 2024
Strings Python are powerful tools for text manipulation. They can be sliced, indexed, and modified using various methods. Understanding how to work with strings is crucial for handling text data effectively in programming.
Special characters and escape sequences add flexibility to string representation. Unicode conversion functions allow working with a wide range of characters, while and formatting techniques enable complex text processing and presentation.
string[0]
accesses the first character)string[-1]
accesses the last character)string[index]
string[start:end]
start
is the index of the first character to include (inclusive)end
is the index of the last character to exclude (exclusive)start
is omitted, it defaults to the beginning of the string (string[:5]
extracts the first 5 characters)end
is omitted, it defaults to the end of the string (string[2:]
extracts from the 3rd character to the end)\
followed by a specific character or [\n](https://www.fiveableKeyTerm:\n)
inserts a newline[\t](https://www.fiveableKeyTerm:\t)
inserts a tab\\
inserts a literal backslash\'
inserts a single quote\"
inserts a double quoter
or R
) treat backslashes as literal characters, ignoring escape sequences (r"C:\newfile"
preserves the backslashes)[ord()](https://www.fiveableKeyTerm:ord())
function takes a single character as an argument and returns its Unicode code point
ord('A')
returns 65
ord('€')
returns 8364
[chr()](https://www.fiveableKeyTerm:chr())
function takes a Unicode code point as an argument and returns the corresponding character
chr(65)
returns 'A'
chr(8364)
returns '€'
ord('A') < ord('B')
evaluates to True
chr(ord('A') + 1)
returns 'B'
+
operator*
operator<
, >
, <=
, >=
, ==
, !=
can be used to compare stringslower()
, upper()
, strip()
, split()
, join()
f"Hello, {name}!"
for inline variable substitution.format()
method: "Hello, {}!".format(name)
for more complex formatting