Python Strings

Strings are the sequence of characters wrapped between quotes. They are one of the most common types in Python. They consist of multiple methods and operations related to their manipulation.

Each character is encoded in the ASCII or Unicode character. So we can say that Python strings are also called the collection of Unicode characters.

In Python, strings can be created by enclosing the character or the sequence of characters in the quotes. Python allows us to use single quotes, double quotes, or triple quotes to create the string.

1. Creating Strings

Strings can be created using:

  • Single quotes ('):
my_string = 'Hello, World!'
  • Double quotes ("):
my_string = "Hello, World!"
  • Triple quotes (''' or """): Useful for multi-line strings:
my_string = '''This is a
multi-line string.'''

2. String Properties

  • Immutable: Strings cannot be changed after creation. Any modification creates a new string.
my_string = "Hello"
my_string[0] = 'h'  # This will raise an error.
  • Ordered: Strings are ordered, meaning you could access elements using indexing and slicing.
  • Iterable: You can iterate over strings by using loops.

3. Accessing String Characters

Indexing

Python uses zero-based indexing.

my_string = "Python"
print(my_string[0]) # Output: P
print(my_string[-1]) # Output: n (last character)

Slicing

Slicing allows extracting parts of the string.

my_string = "Python"
print(my_string[0:3]) # Output: Pyt (characters 0, 1, 2)
print(my_string[::2]) # Output: Pto (every second character)

4. Common String Operations

Concatenation

Joining two or more strings using + .

greet = "Hello, " + "World!"
print(greet) # Output: Hello, World!

Repetition

Repeating a string using * .

repeat = "Ha" * 3
print(repeat) # Output: HaHaHa

Membership

Checking if a substring exists.

print("Py" in "Python") # Output: True
print("java" not in "Python") # Output: True

5. String Methods

Strings come with built-in methods for manipulation:

MethodDescription
.lower()Converts all characters to lowercase.
.upper()Converts all characters to uppercase.
.strip()Removes whitespace or specific characters.
.replace(a, b)Replaces a with b.
.split()Splits a string into a list by spaces or a delimiter.
.join()Joins elements of a list into a string.
.find(sub)Returns the index of the first occurrence of sub.
.startswith(prefix)Checks if string starts with prefix.
.endswith(suffix)Checks if string ends with suffix.
.count(sub)Counts occurrences of sub.

Examples:

s = " Hello, Python! "

print(s.lower()) # " hello, python! "
print(s.strip()) # "Hello, Python!"
print(s.replace("Hello", "Hi")) # " Hi, Python! "
print(s.split(',')) # [' Hello', ' Python!']
print(', '.join(['1', '2', '3'])) # "1, 2, 3"

6. Formatting Strings

f-strings (Python 3.6+)

Embed expressions in strings.

name = "Alice"
age = 25
print(f"My name is {name} and I am {age} years old.")

format() Method

print("My name is {} and I am {} years old.".format(name, age))

7. Escape Sequences

Escape sequences are used to include special characters.

SequenceMeaning
\'Single quote
\"Double quote
\\Backslash
\nNew line
\tTab

Example:

print("Hello\nWorld") # Output:
#Hello
#World

8. Raw Strings

Prefix a string with r to treat backslashes literally.

raw = r"C:\new_folder"
print(raw) # Output: C:\new_folder

9. Useful Tips

  • Iterating Through Strings:
for char in "Python":
print(char)
  • String Length: Use len() to find the number of characters.
print(len("Python")) # Output: 6
  • Checking Content:
print("123".isdigit()) # True
print("abc".isalpha()) # True
print("Hello123".isalnum()) # True