Python Strings

Strings in Python are sequences of characters enclosed in either single quotes (') or double quotes ("). They are used to store textual data like names, addresses, file paths, etc, in your program.

Creating a String

To create a string, you enclose the text in single or double quotes.

For example:

name = 'James'
city = "London"

Empty String

An empty string in Python is a string with no characters, written as '' or "".

For example:

empty_string = ""

Multiline Strings

You can create multiline strings using triple single quotes (''') or triple double quotes (""").

For example:

multiline_string = """Hello! My name is James.
I live here in London. 
It is a beatiful weather today."""
print(multiline_string)

Output:

Hello! My name is James.
I live here in London. 
It is a beatiful weather today.

Accessing Characters in a String

Strings in Python are sequences of Unicode characters, therefore, you can access individual characters using indexing. Each character in the string has a position (starting from 0).

For example:

fruit = "apple"
first_letter = fruit[0]
second_letter = fruit[1]

print(first_letter)  # Output: a
print(second_letter) # Output: b

Python strings also support negative indexing, where the last character is at index -1, the second last at -2, and so on.

For example:

fruit = "apple"

last_letter = fruit[-1]
second_last_letter = fruit[-2]

print(last_letter)        # Output: e
print(second_last_letter) # Output: l

String Slicing

String slicing allows you to extract a portion of a string (substring) by specifying a range of indices.

The basic syntax is:

string[start:stop:step]

Where:

start (Optional): The index where the slicing begins (inclusive). If omitted, it defaults to 0.

stop (Optional): The index where the slicing ends (exclusive). If omitted, it defaults to the length of the string.

step (Optional): The interval between characters. Default is 1.

For example:

fruit = "pineapple"

substring = fruit[:3]
print(substring) # Output: pin

In the above code example, the start index is omitted, which means the slicing begins from the very first character of the string, i.e., index 0. The end index is 3, meaning the slice will include characters from the index 0 up to, but not including, index 3. Therefore, it extracts the characters at indices 0, 1, and 2, resulting in a substring "pin".

Python Strings are Immutable

Strings in Python are immutable, meaning you cannot modify the characters of a string.

The code below causes TypeError.

fruit = "pineapple"

fruit[0] = 'n' # Causes TypeError

However, you can assign the same variable a different value.

fruit = "pineapple"

fruit = "mango"
print(fruit) # Output; mango

String Concatenation

You can concatenate (join or combine) two or more strings using the + operator.

For example:

a = "pine"
b = "apple"

c = a + b
print(c) # Output: pineapple

Iterate Through a String

You can iterate through each character of a string using a for loop.

For example:

fruit = "apple"

for char in fruit:
    print(char)

Output:

a
p
p
l
e

String Length

You can get the length of a string using the len() function.

For example:

fruit = "apple"

fruit_length = len(fruit)
print(fruit_length) # Output: 5

Checking if a String Contains a Substring or a Character

You can check if a string contains a substring or a character using the in operator.

For example:

fruit = "apple"

if 'p' in fruit:
    print("Character found")
else: 
    print("Character not found")

message = "Give money to James"

if "money" in message:
    print("Substring found")
else:
    print("Substring not found")

Output:

Character found
Substring found

Similarly, you can check if a string doesn’t contain a substring or a character using the not in operator.

For example:

message = "give money to James"

if "money" not in message:
    print("Don't give money to James")
else:
    print("Give money to James")

Output:

Give money to James

The in and not in operators are case-sensitive, meaning "money" and "Money" would be treated as different strings.

String Methods

Python offers various built-in methods for working with strings. In this section, we will focus on the most commonly used ones.

lower(): Converts all characters in the string to lowercase.

upper(): Converts all characters in the string to uppercase.

strip(): Removes leading and trailing whitespace (or specific characters) from the string.

split(): Splits the string into a list using the specific separator (default is any whitespace).

find(): Returns the index of the first occurrence of the specified substring, or -1 if not found.

replace(old, new): Replaces all occurrences of a substring (old) with another substring (new).

For example:

text = "Apple"

# Convert to lowercase
lower_text = text.lower()
print(lower_text) # Output: apple

# Convert to uppercase
upper_text = text.upper()
print(upper_text) # Output: APPLE

text2 = "  I love Python  "

# Strip the leading and trailing whitespaces
stripped_text = text.strip()
print(stripped_text) # Output: I love Python

text3 = "Python is awesome"

# Split the string into a list (default splits at spaces)
split_text = text3.split() 
print(split_text) # Output: ['Python', 'is', 'awesome']

# Find index of the substring 
index = text3.find("awesome")
print(index) # Output: 10

# Replace all occurences of the substring
replaced_text = text3.replace("awesome", "cool")
print(replaced_text) # Output: Python is cool

Format String (f-string)

In Python, f-string allows you to insert variables or expressions into strings.

For example:

name = "James"
age = 35

print(f"My name is {name} and I am {age} years old.")
# Output: My name is James and I am 35 years old.

String Escape Sequences

Escape sequences are special characters preceded by a backslash (\) used to represent characters that are difficult or impossible to represent directly.

For example:

# Newline
print("apple\nbanana\nmango")

# Tab
print("Salary \t 5000")

# Single or double quotes
print('It\'s raining today')
print("He said, \"Hello\"")

Output:

apple
banana
mango
Salary 	 5000
It's raining today
He said, "Hello"

Here is a table of escape sequences:

Escape SequenceDescriptionExample Output
\\Backslash\
\'Single quote'
\"Double quote"
\nNewlineLine break
\tHorizonal tabAdds a tab space
\rCarriable returnCursor to line start
\bBackspaceDeletes previous character
\fFormfeedPage break
\vVertical tabMoves cursor down
\oooOctal value\141a
\xhhHexadecimal value\x61a