Skip to content

Python Strings

Strings are one of the most commonly used data types in Python. They are immutable sequences composed of characters, used to represent text information.

Creating Strings

You can create strings using single quotes ', double quotes ", or triple quotes '''/""".

python
# Using single quotes
name1 = 'Alice'

# Using double quotes
name2 = "Bob"

# Using triple quotes to create multi-line strings
message = """
This is a multi-line string.
It can span across several lines.
"""

print(name1)
print(name2)
print(message)

Single quotes and double quotes can be nested within each other, which is very useful when the string contains quotes.

python
quote1 = "He said, 'Hello!'"
quote2 = 'She replied, "Hi there!"'

Strings are Sequences

Strings are character sequences, so you can index and slice them just like lists and tuples.

Indexing

Indexing is used to access individual characters in a string. Indexing starts from 0.

python
my_string = "Python"

# Get the first character
print(my_string[0])  # Output: 'P'

# Get the last character
print(my_string[-1])  # Output: 'n'

Slicing

Slicing is used to obtain substrings. The syntax is [start:stop:step].

python
my_string = "Hello, World!"

# Get characters from index 2 to index 4
print(my_string[2:5])   # Output: 'llo'

# From the beginning to index 4
print(my_string[:5])    # Output: 'Hello'

# From index 7 to the end
print(my_string[7:])    # Output: 'World!'

# Get the entire string
print(my_string[:])     # Output: 'Hello, World!'

# Get every other character
print(my_string[::2])   # Output: 'Hlo ol!'

# Reverse the string
print(my_string[::-1])  # Output: '!dlroW ,olleH'

Common String Methods

Python provides many built-in methods for strings to perform common operations. Note that since strings are immutable, all these methods return a new string and do not modify the original string.

  • len(s): Returns the length of the string.
  • s.upper(): Returns the uppercase version of the string.
  • s.lower(): Returns the lowercase version of the string.
  • s.strip(): Removes whitespace characters from the beginning and end of the string.
  • s.split(sep): Splits the string into a list by the specified separator sep.
  • sep.join(iterable): Joins all elements in an iterable (such as a list) using the specified separator sep.
  • s.replace(old, new): Replaces the old substring with the new substring in the string.
  • s.startswith(prefix): Checks whether the string starts with prefix.
  • s.endswith(suffix): Checks whether the string ends with suffix.
  • s.find(sub): Finds the first occurrence position of substring sub in the string; returns -1 if not found.

Example:

python
text = "  python is fun!  "

print(len(text))              # Output: 18
print(text.upper())           # Output: '  PYTHON IS FUN!  '
print(text.strip())           # Output: 'python is fun!'
print(text.strip().split(' '))# Output: ['python', 'is', 'fun!']
print("-".join(['a', 'b', 'c'])) # Output: 'a-b-c'
print(text.replace('fun', 'awesome')) # Output: '  python is awesome!  '

String Formatting

Embedding variable values into strings is a very common requirement. Python provides several ways to achieve this. The most modern and recommended method is using f-strings.

f-strings (Formatted String Literals)

Add an f or F before the opening quote of the string, then you can directly reference variables using curly braces {} in the string.

python
name = "Eric"
age = 30

# Using f-string
message = f"My name is {name} and I am {age} years old."
print(message) # Output: My name is Eric and I am 30 years old.

# f-strings can also evaluate expressions
print(f"Next year, I will be {age + 1}.") # Output: Next year, I will be 31.

Due to their simplicity and efficiency, f-strings are the preferred formatting method in Python 3.6+ versions.

Content is for learning and research only.