Python Strings

A string in Python is a sequence of characters enclosed within quotes. It is an immutable data type, meaning once a string is created, it cannot be changed. Any operation that modifies a string actually creates a new one.

Python strings are used for storing and manipulating text-based data such as names, addresses, messages, file paths, and user input.

Creating a String

To create a string, you enclose text in single quotes (') or double quotes (").

For example:

name = 'james'
hobby = "running"

Empty String

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

For example:

empty_string = ""

Multiline Strings

Multiline strings are used to store or display text that spans multiple lines, such as messages or instructions.

You can create a multiline string by using triple quotes – either 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)

Accessing Characters in a String

In Python, you can access string characters using indexing or slicing.

Accessing Single Characters With Indexing

Python uses zero-based indexing, so the first character is at index 0, the second at index 1 and so on.

For example:

fruit = "apple"
print(fruit[0]) # Output: a
print(fruit[1]) # Output: p

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"
print(fruit[-1]) # Output: e
print(fruit[-2]) # Output: l

Accessing Substrings With Slicing

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

The basic syntax of slicing 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 01, and 2, resulting in a substring "pin".

Note that a slice always includes the character at the start index, but excludes the character at the end index.

Let’s take a look at another example with a step value.

For example:

fruit = "pineapple"

substring = fruit[::2]
print(substring) # Output: pnape

In this code example, both the start and end indices are omitted, which means the slicing begins from the very first character of the string and continues to the end. The step value is 2, which means it selects every second character from the string. Therefore, it extracts the characters at indices 0, 2, 4, 6, and 8, resulting in the substring "pnape".

String Concatenation

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

For example:

a = "Hello"
b = "World"
message = a + b
print(message) # HelloWorld

To add a space between two strings, you can insert a space " " between them when concatenating.

For example:

a = "Hello"
b = "World"
message = a + " " + b
print(message) # Hello World

String Multiplication (Repetition)

String multiplication (also known as string repetition) is a feature that allows you to repeat a string a specified number of times using the * operator.

For example:

print(3*"Hello")

Output:

HelloHelloHello

If you want to print text on different lines, you can use the newline character (\n) at the end of the string.

For example:

print(3*"Hello\n")

Output:

Hello
Hello
Hello

Iterate Through a String

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

For example:

fruit = "apple"
for char in "apple":
    print(char)

Output:

a
p
p
l
e

Note: If you are not familiar with for loop yet, that is perfectly okay! We will cover them in detail later in this tutorial.

String Length

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

For example:

fruit = "apple"
print(len(fruit)) # Output: 5

Format String (f-string)

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

To use f-string, add an f (or F) before the opening quote, and put any variables or expressions inside curly braces {}.

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.

Check if a String Contains a Substring

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

For example:

text = "Hello World"
print("H" in text)     # Output: True
print("World" in text) # Output: True
print("apple" in text) # Output: False

String Methods

Python comes with various built-in string methods for string manipulation that allow you to easily change the case of the text, find or replace words, remove spaces, split a string into parts, and more.

In this section, we will discuss only the most common ones.

lower()

Converts all characters in the string to lowercase.

For example:

text = "Hello World"
print(text.lower()) # Output: hello world

upper()

Converts all characters in the string to uppercase.

For example:

text = "Hello World"
print(text.upper()) # Output: HELLO WORLD

title()

Converts the first letter of each word to uppercase.

For example:

text = "hello how are you"
print(text.title()) # Output: Hello How Are You

capitalize()

Converts the first letter of the entire string to uppercase and the rest to lowercase.

For example:

text = "hello world"
print(text.capitalize()) # Output: Hello world

find()

Returns the index of the first occurrence of the substring. Returns -1 if the substring is not found.

For example:

text = "hello world"
print(text.find("world")) # Output: 6
print(text.find("apple")) # Output: -1

startswith()

Returns True if the string starts with the specified prefix.

For example:

text = "hello world"
print(text.startswith("hello")) # Output: True
print(text.startswith("apple")) # Output: False

endswith()

Returns True if the string ends with the specified suffix.

For example:

text = "hello world"
print(text.endswith("world")) # Output: True
print(text.endswith("apple")) # Output: False

count()

Returns the number of occurrences of the specified substring.

For example:

text = "world hello world"
print(text.count("world")) # Output: 2

replace()

Replaces all the occurrences of a substring with another string.

For example:

text = "world hello world"
print(text.replace("world", "apple")) # Output: apple hello apple

strip()

Removes all leading and trailing characters (whitespace by default).

For example:

text = "    hello    "
print(text.strip()) # Output: hello

split()

Splits a string into a list using a delimiter (default is whitespace).

For example:

text = "python is awesome"
print(text.split()) # Output: ['python', 'is', 'awesome']

isdigit()

Returns True if all characters in a string are digits.

For example:

text = "12345"
print(text.isdigit()) # Output: True

isalpha()

Returns True if all characters in a string are alphabetic (a-z and A-Z).

For example:

text = "apple"
print(text.isalpha()) # Output: True

isalnum()

Return True if all characters in a string are letters or digits.

For example:

text = "iphone17"
print(text.isalnum()) # Output: True

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 (\n is a newline escape sequence)
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
\rCarriage returnCursor to line start
\bBackspaceDeletes previous character
\fFormfeedPage break
\vVertical tabMoves cursor down
\oooOctal value\141a
\xhhHexadecimal value\x61a