Python provides powerful and flexible string manipulation capabilities. Strings in Python are sequences of characters enclosed in either single ('), double ("), or triple (''' """) quotes.


Creating Strings

Strings can be created in multiple ways:

string1 = 'Hello'
string2 = "World"
string3 = '''This is
a multiline string'''

print(string1)  # Hello
print(string2)  # World
print(string3)
# This is
# a multiline string

Special Characters: Escape Sequences

Python supports special characters using escape sequences:

  • \n - New line;
  • \t - Tab (indentation);
  • \\ - Backslash;
  • \' - Single quote;
  • \" - Double quote;
  • \r - Carriage return;
  • \b - Backspace;
  • \f - Form feed;
  • \ooo - Octal value;
  • \xhh - Hexadecimal value;
text = "Hello\nWorld\tPython\\Programming"
print(text)

# Hello
# World    Python\Programming

String Indexing & Slicing

- Indexing: Accessing Characters

Python allows access to individual characters in a string using indexing:

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

Slicing: Extracting Substrings

You can extract parts of a string using slicing:

word = "Programming"
print(word[0:4])   # Prog
print(word[:6])    # Progra (start from 0)
print(word[3:])    # gramming (start from index 3 to end)
print(word[-3:])   # ing (last 3 characters)
print(word[::2])   # Pormig (every 2nd character)

String Concatenation & Repetition

Python allows concatenating (joining) strings using + and repeating strings using *:

str1 = "Hello"
str2 = "World"
print(str1 + " " + str2)  # Hello World

print(str1 * 3)  # HelloHelloHello

Modifying Strings

Uppercase, Lowercase, Title Case

text = "python programming"
print(text.upper())   # PYTHON PROGRAMMING
print(text.lower())   # python programming
print(text.title())   # Python Programming

Stripping Whitespace

text = "   Hello World   "
print(text.strip())   # "Hello World"
print(text.lstrip())  # "Hello World   "
print(text.rstrip())  # "   Hello World"
s = "hello world"
print(s.capitalize())  # Hello world

s = "HeLLo WoRLd"
print(s.swapcase())  # hEllO wOrlD

s = "Python is great"
print(s.startswith("Python"))  # True

s = "Python is great"
print(s.endswith("great"))  # True

s = "hello world"
print(s.find("o"))  # 4

Checking Substrings

text = "Python is awesome"
print("Python" in text)   # True
print("Java" not in text) # True

Finding & Counting

text = "Python programming is fun"
print(text.find("programming"))  # 7 (index where it starts)
print(text.count("n"))  # 3 (number of occurrences)

Replacing & Splitting Strings

Replacing Substrings

text = "I love Java"
new_text = text.replace("Java", "Python")
print(new_text)  # I love Python

Splitting and Joining Strings

text = "apple,banana,grape"
words = text.split(",")
print(words)  # ['apple', 'banana', 'grape']

joined = " - ".join(words)
print(joined)  # apple - banana - grape

String Formatting

Python provides multiple ways to format strings.

Old-style Formatting (%)

name = "Alice"
age = 25
print("Name: %s, Age: %d" % (name, age))
# Name: Alice, Age: 25

format() Method

name = "Alice"
age = 25

print("Name: {}, Age: {}".format(name, age))
# Name: Alice, Age: 25

print("Name: {1}, Age: {0}".format(age, name))
# Name: Alice, Age: 25

f-Strings (Python 3.6+)

f-Strings provide a more concise way to format strings:

name = "Alice"
age = 25
print(f"Name: {name}, Age: {age}")
# Name: Alice, Age: 25

- Using expressions inside f-Strings:

a = 5
b = 10
print(f"Sum: {a + b}")  # Sum: 15

- Formatting Numbers:

pi = 3.14159
print(f"Pi: {pi:.2f}")  # Pi: 3.14

Raw Strings (r prefix)

Raw strings ignore escape sequences:

path = r"C:\Users\Name\Documents"
print(path)
# C:\Users\Name\Documents

Multi-line Strings & Docstrings

text = """This is a
multi-line string"""

def greet():
    """This is a docstring.
    It describes the function."""
    return "Hello"

Checking String Properties

text = "Hello123"

print(text.isalpha())  # False (contains numbers)
print(text.isdigit())  # False (contains letters)
print(text.isalnum())  # True (letters + numbers)
print(text.isspace())  # False (not just spaces)

print("hello".islower())  # True
print("HELLO".isupper())  # True
print("Title Case".istitle())  # True

Length of String

s = "Python"
print(len(s))  # 6

Reversing a String

text = "Python"
print(text[::-1])  # nohtyP

Iterating Over a String

text = "Python"

for char in text:
    print(char)

Converting Between Strings and Lists

# Convert string to list
text = "Hello"
char_list = list(text)
print(char_list)  # ['H', 'e', 'l', 'l', 'o']

# Convert list to string
char_list = ['H', 'e', 'l', 'l', 'o']
text = "".join(char_list)
print(text)  # Hello

Python provides a rich set of string manipulation features, including indexing, slicing, formatting, escape sequences, and built-in methods. Using these efficiently can help you process and format text in various applications.