Python Strings

Strings are a fundamental data type in Python, used to represent text. Strings in Python are sequences of characters, making them iterable, and are enclosed in either single quotes (`'`), double quotes (`"`), or triple quotes (`'''` or `"""`) for multi-line strings. Strings are immutable, meaning they cannot be changed after creation. This guide covers string creation, indexing, slicing, common methods, formatting, and other useful features in Python.

Creating Strings

Strings can be created with single, double, or triple quotes. Triple quotes are especially useful for multi-line strings.
# Single-line strings
string1 = 'Hello, World!'
string2 = "Python Strings"

# Multi-line string
multi_line_string = '''This is a
multi-line
string in Python.'''

print(string1)
print(string2)
print(multi_line_string)

Output:
Hello, World!
Python Strings
This is a
multi-line
string in Python.


Accessing Characters in Strings

Each character in a string has an index, starting at 0 for the first character. You can access individual characters or use negative indices to start from the end of the string.
greeting = "Hello"
print("First character:", greeting[0])   # First character
print("Last character:", greeting[-1])   # Last character

Output:
First character: H
Last character: o


String Slicing

Python allows you to extract substrings from a string using the slicing syntax `[start:stop:step]`.
text = "Python Programming"
print("Characters 0 to 5:", text[0:6])  # Slice from index 0 to 5
print("Every second character:", text[::2])  # Slice with step
print("Reverse string:", text[::-1])  # Reverse the string

Output:
Characters 0 to 5: Python
Every second character: Pto rgamn
Reverse string: gnimmargorP nohtyP


String Concatenation and Repetition

Concatenation joins two or more strings, while repetition repeats a string a specified number of times.
str1 = "Hello"
str2 = "World"
concatenated = str1 + " " + str2
repeated = str1 * 3

print("Concatenated string:", concatenated)
print("Repeated string:", repeated)

Output:
Concatenated string: Hello World
Repeated string: HelloHelloHello


Common String Methods

Python provides a range of built-in string methods for common operations like changing case, finding substrings, and replacing text.
sample_text = "Python Programming"

# Convert to uppercase
print("Uppercase:", sample_text.upper())

# Convert to lowercase
print("Lowercase:", sample_text.lower())

# Find a substring
print("Position of 'Prog':", sample_text.find("Prog"))

# Replace a substring
print("Replace 'Python' with 'Java':", sample_text.replace("Python", "Java"))

Output:
Uppercase: PYTHON PROGRAMMING
Lowercase: python programming
Position of 'Prog': 7
Replace 'Python' with 'Java': Java Programming


String Formatting

Python offers several ways to format strings, such as using `f-strings`, `format()`, or the `%` operator. `f-strings` (formatted string literals) are recommended for readability and efficiency.
name = "Alice"
age = 30

# Using f-string
print(f"My name is {name} and I am {age} years old.")

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

# Using % operator
print("My name is %s and I am %d years old." % (name, age))

Output:
My name is Alice and I am 30 years old.
My name is Alice and I am 30 years old.
My name is Alice and I am 30 years old.


Checking for Substrings

Use `in` and `not in` to check if a substring is present or absent in a string.
text = "Python programming is fun"
print("Contains 'Python':", 'Python' in text)
print("Contains 'Java':", 'Java' in text)

Output:
Contains 'Python': True
Contains 'Java': False


Splitting and Joining Strings

Use `split()` to divide a string into a list of substrings, and `join()` to combine a list of strings into a single string.
sentence = "Python is great for programming"
words = sentence.split()  # Splits by spaces by default
print("Split into words:", words)

# Joining words with hyphen
joined_sentence = "-".join(words)
print("Joined with hyphen:", joined_sentence)

Output:
Split into words: ['Python', 'is', 'great', 'for', 'programming']
Joined with hyphen: Python-is-great-for-programming


Trimming Strings

Use `strip()`, `lstrip()`, and `rstrip()` to remove whitespace (or specific characters) from the beginning and/or end of a string.
text_with_spaces = "   Hello, Python!   "
print("Original:", text_with_spaces)
print("Strip all:", text_with_spaces.strip())
print("Left strip:", text_with_spaces.lstrip())
print("Right strip:", text_with_spaces.rstrip())

Output:
Original: Hello, Python!
Strip all: Hello, Python!
Left strip: Hello, Python!
Right strip: Hello, Python!


Counting Occurrences

The `count()` method counts the number of times a substring appears in a string.
text = "Python is fun. Python is easy to learn."
print("Occurrences of 'Python':", text.count("Python"))

Output:
Occurrences of 'Python': 2


String Immutability

Strings are immutable, meaning that once created, they cannot be modified. Any "modification" creates a new string.
original = "Hello"
modified = original.replace("H", "J")
print("Original String:", original)
print("Modified String:", modified)

Output:
Original String: Hello
Modified String: Jello

Explanation: The original string `original` remains unchanged, demonstrating that strings are immutable.

Summary

Python strings offer powerful tools for handling text, including indexing, slicing, and various methods for modification, searching, and formatting. Understanding these features is essential for effective text processing and data handling in Python programming.

Previous: Python Loops | Next: Python Exception Handling

<
>