Strings In Python
Python Strings: Comprehensive Theory
Strings in python are surrounded by either single quotation marks, or double quotation marks. 'hello' is the same as "hello".
1. Creating Strings
You can display a string literal with the print() function:
print("Hello")
print('Hello')
Multiline Strings
You can assign a multiline string to a variable by using three quotes (single or double).
a = """Lorem ipsum dolor sit amet,
consectetur adipiscing elit,
sed do eiusmod tempor incididunt
ut labore et dolore magna aliqua."""
2. Strings are Arrays
Like many other popular programming languages, strings in Python are arrays of bytes representing unicode characters. However, Python does not have a character data type, a single character is simply a string with a length of 1.
Accessing Characters
Square brackets can be used to access elements of the string.
a = "Hello, World!"
print(a[1]) # Output: e
3. String Slicing
You can return a range of characters by using the slice syntax. Specify the start index and the end index, separated by a colon, to return a part of the string.
b = "Hello, World!"
print(b[2:5]) # llo (from index 2 to 5, not including 5)
Slice From the Start/End
b[:5](Get characters from the start to index 5)b[2:](Get characters from index 2 to the end)b[-5:-2](Negative indexing to start slice from the end)
4. Modifying Strings
Python has a set of built-in methods that you can use on strings.
| Method | Description |
| :--- | :--- |
| upper() | Returns the string in upper case |
| lower() | Returns the string in lower case |
| strip() | Removes any whitespace from the beginning or the end |
| replace() | Replaces a string with another string |
| split() | Splits the string into substrings if it finds instances of the separator |
a = " Hello, World! "
print(a.strip()) # "Hello, World!"
print(a.replace("H", "J")) # "Jello, World!"
5. String Concatenation
To concatenate, or combine, two strings you can use the + operator.
a = "Hello"
b = "World"
c = a + " " + b
print(c) # Hello World
6. String Formatting (f-strings)
As of Python 3.6, f-strings are the preferred way to format strings. To specify a string as an f-string, simply put an f in front of the string literal, and add curly brackets {} as placeholders for variables and other operations.
age = 36
txt = f"My name is John, and I am {age}"
print(txt)
7. Escape Characters
To insert characters that are illegal in a string, use an escape character. An escape character is a backslash \ followed by the character you want to insert.
| Code | Result |
| :--- | :--- |
| \' | Single Quote |
| \" | Double Quote |
| \\ | Backslash |
| \n | New Line |
| \t | Tab |
| \b | Backspace |