0% found this document useful (0 votes)
2 views10 pages

Python String Operations

This document serves as a comprehensive reference for Python string operations, covering string creation, indexing, slicing, and various methods for case conversion, searching, replacing, splitting, and joining strings. It also discusses advanced operations such as string validation, translation, encoding/decoding, and performance tips for string concatenation and comparison. The document emphasizes the importance of mastering these operations for efficient text processing in Python.

Uploaded by

S SA
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views10 pages

Python String Operations

This document serves as a comprehensive reference for Python string operations, covering string creation, indexing, slicing, and various methods for case conversion, searching, replacing, splitting, and joining strings. It also discusses advanced operations such as string validation, translation, encoding/decoding, and performance tips for string concatenation and comparison. The document emphasizes the importance of mastering these operations for efficient text processing in Python.

Uploaded by

S SA
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 10

Python String Operations Reference

By Engr Aamir Jamil

String Creation and Basic Operations

Creating Strings

python

# Different ways to create strings


single_quote = 'Hello World'
double_quote = "Hello World"
triple_quote = """Multi-line
string example"""
raw_string = r"C:\Users\Name\file.txt" # Raw string
f_string = f"Hello {name}" # Formatted string

String Indexing and Slicing

python

text = "Python Programming"


# Indexing
first_char = text[0] # 'P'
last_char = text[-1] # 'g'

# Slicing [start:end:step]
substring = text[0:6] # 'Python'
reverse = text[::-1] # 'gnimmargorP nohtyP'
every_second = text[::2] # 'Pto rgamn'
String Methods - Case Operations

Case Conversion

python

text = "Python Programming"

# Case methods
upper_text = text.upper() # 'PYTHON PROGRAMMING'
lower_text = text.lower() # 'python programming'
title_text = text.title() # 'Python Programming'
capitalize_text = text.capitalize() # 'Python programming'
swapcase_text = text.swapcase() # 'pYTHON pROGRAMMING'

Case Checking

python

text = "Hello123"

# Check case methods


text.isupper() # False
text.islower() # False
text.istitle() # True
text.isalpha() # False (contains numbers)
text.isdigit() # False
text.isalnum() # True (alphanumeric)
String Methods - Searching and Finding

Finding Substrings

python

text = "Python is awesome and Python is powerful"

# Find methods
index = text.find("Python") # 0 (first occurrence)
last_index = text.rfind("Python") # 22 (last occurrence)
count = text.count("Python") #2

# Check if string contains


contains = "awesome" in text # True
starts = text.startswith("Python") # True
ends = text.endswith("powerful") # True

Replace Operations

python

text = "Hello World Hello"

# Replace methods
new_text = text.replace("Hello", "Hi") # 'Hi World Hi'
first_only = text.replace("Hello", "Hi", 1) # 'Hi World Hello'
String Methods - Splitting and Joining

Splitting Strings

python

text = "apple,banana,orange"
csv_text = "name:age:city"

# Split methods
fruits = text.split(",") # ['apple', 'banana', 'orange']
parts = csv_text.split(":") # ['name', 'age', 'city']
words = "hello world".split() # ['hello', 'world'] (default whitespace)
lines = "line1\nline2\nline3".splitlines() # ['line1', 'line2', 'line3']

# Partition (splits into 3 parts)


before, sep, after = "[email protected]".partition("@") # 'name', '@', 'email.com'

Joining Strings

python

# Join method
fruits = ["apple", "banana", "orange"]
joined = ", ".join(fruits) # 'apple, banana, orange'
path = "/".join(["home", "user", "documents"]) # 'home/user/documents'

String Methods - Whitespace Operations

Whitespace Handling

python
text = " Hello World "

# Remove whitespace
stripped = text.strip() # 'Hello World'
left_strip = text.lstrip() # 'Hello World '
right_strip = text.rstrip() # ' Hello World'

# Remove specific characters


cleaned = "...Hello...".strip(".") # 'Hello'

Padding and Alignment

python

text = "Python"

# Padding methods
left_pad = text.ljust(10, "-") # 'Python----'
right_pad = text.rjust(10, "-") # '----Python'
center_pad = text.center(10, "-") # '--Python--'
zero_pad = "42".zfill(5) # '00042'

String Formatting

Old Style Formatting (% operator)

python

name = "Aamir"
age = 30
text = "My name is %s and I am %d years old" % (name, age)
.format() Method

python

# Positional arguments
text = "Hello {0}, you are {1} years old".format("Aamir", 30)

# Named arguments
text = "Hello {name}, you are {age} years old".format(name="Aamir", age=30)

# Number formatting
price = 19.99
formatted = "Price: ${:.2f}".format(price) # 'Price: $19.99'

F-Strings (Recommended - Python 3.6+)

python
name = "Aamir"
age = 30
price = 19.99

# Basic f-string
text = f"Hello {name}, you are {age} years old"

# With expressions
text = f"Next year you'll be {age + 1}"

# With formatting
text = f"Price: ${price:.2f}"

# With method calls


text = f"Name in caps: {name.upper()}"

Advanced String Operations

String Validation Methods

python

text = "Hello123"

# Character type checking


text.isalpha() # False (contains numbers)
text.isdigit() # False (contains letters)
text.isalnum() # True (alphanumeric)
text.isspace() # False
text.isprintable() # True
text.isidentifier() # False (not valid Python identifier)
String Translation

python

# Create translation table


translator = str.maketrans("aeiou", "12345")
text = "hello world"
translated = text.translate(translator) # 'h2ll4 w4rld'

# Remove characters
remove_vowels = str.maketrans("", "", "aeiou")
no_vowels = "hello world".translate(remove_vowels) # 'hll wrld'

String Encoding/Decoding

python

text = "Hello World"

# Encode to bytes
encoded = text.encode('utf-8') # b'Hello World'
encoded_latin = text.encode('latin-1')

# Decode from bytes


decoded = encoded.decode('utf-8') # 'Hello World'

String Constants (from string module)

python
import string

# Useful string constants


string.ascii_letters # 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
string.ascii_lowercase # 'abcdefghijklmnopqrstuvwxyz'
string.ascii_uppercase # 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
string.digits # '0123456789'
string.punctuation # '!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~'
string.whitespace # ' \t\n\r\x0b\x0c'

Performance Tips

String Concatenation

python

# Inefficient (creates new string objects)


result = ""
for i in range(1000):
result += str(i)

# Efficient (use join)


numbers = [str(i) for i in range(1000)]
result = "".join(numbers)

# For few strings, + is fine


result = "Hello" + " " + "World"

String Comparison

python
# Case-insensitive comparison
text1.lower() == text2.lower()

# Check if string is empty


if not text: # Better than if text == ""
print("String is empty")

Master these string operations for efficient text processing in Python

You might also like