python
examples
examples.py🐍python
"""
02 - Strings: Examples
Run this file to see all string operations in action!
"""
print("=" * 60)
print("STRINGS - EXAMPLES")
print("=" * 60)
# =============================================================================
# 1. STRING CREATION
# =============================================================================
print("\n--- 1. String Creation ---\n")
# Different ways to create strings
single_quotes = 'Hello World'
double_quotes = "Hello World"
triple_single = '''Multi-line
string with
single quotes'''
triple_double = """Multi-line
string with
double quotes"""
print(f"Single quotes: {single_quotes}")
print(f"Double quotes: {double_quotes}")
print(f"Triple quotes:\n{triple_single}")
# Strings with quotes inside
mixed1 = "He said 'Hello'"
mixed2 = 'She said "Hi"'
escaped = "Both 'single' and \"double\" quotes"
print(f"\nMixed quotes: {mixed1}")
print(f"Mixed quotes: {mixed2}")
print(f"Escaped: {escaped}")
# =============================================================================
# 2. STRING INDEXING
# =============================================================================
print("\n--- 2. String Indexing ---\n")
text = "Python"
print(f"String: '{text}'")
print(f"Length: {len(text)}")
# Show index positions
print("\nIndex positions:")
print("Char: ", end="")
for char in text:
print(f" {char} ", end="")
print()
print("Index: ", end="")
for i in range(len(text)):
print(f" {i} ", end="")
print()
print("Neg: ", end="")
for i in range(-len(text), 0):
print(f"{i} ", end="")
print()
# Accessing characters
print(f"\ntext[0] = '{text[0]}'")
print(f"text[2] = '{text[2]}'")
print(f"text[-1] = '{text[-1]}'")
print(f"text[-3] = '{text[-3]}'")
# =============================================================================
# 3. STRING SLICING
# =============================================================================
print("\n--- 3. String Slicing ---\n")
text = "Python Programming"
print(f"String: '{text}'")
# Basic slicing
print(f"\ntext[0:6] = '{text[0:6]}'") # Python
print(f"text[7:18] = '{text[7:18]}'") # Programming
print(f"text[:6] = '{text[:6]}'") # Python (from start)
print(f"text[7:] = '{text[7:]}'") # Programming (to end)
print(f"text[:] = '{text[:]}'") # Full copy
# Slicing with step
print(f"\ntext[::2] = '{text[::2]}'") # Every 2nd character
print(f"text[1::2] = '{text[1::2]}'") # Every 2nd, starting from index 1
# Negative slicing
print(f"\ntext[-11:] = '{text[-11:]}'") # Programming
print(f"text[:-12] = '{text[:-12]}'") # Python
# Reverse string
print(f"\ntext[::-1] = '{text[::-1]}'") # Reversed
# =============================================================================
# 4. STRING METHODS - CASE
# =============================================================================
print("\n--- 4. Case Methods ---\n")
text = "hello WORLD python"
print(f"Original: '{text}'")
print(f"upper(): '{text.upper()}'")
print(f"lower(): '{text.lower()}'")
print(f"title(): '{text.title()}'")
print(f"capitalize():'{text.capitalize()}'")
print(f"swapcase(): '{text.swapcase()}'")
# =============================================================================
# 5. STRING METHODS - SEARCH
# =============================================================================
print("\n--- 5. Search Methods ---\n")
text = "Hello World, Hello Python, Hello Everyone"
print(f"String: '{text}'")
print(f"\nfind('Hello') = {text.find('Hello')}")
print(f"find('Python') = {text.find('Python')}")
print(f"find('Java') = {text.find('Java')}") # -1 if not found
print(f"rfind('Hello') = {text.rfind('Hello')}") # Rightmost
print(f"\ncount('Hello') = {text.count('Hello')}")
print(f"count('o') = {text.count('o')}")
print(f"\n'Python' in text = {'Python' in text}")
print(f"'Java' in text = {'Java' in text}")
print(f"\nstartswith('Hello') = {text.startswith('Hello')}")
print(f"endswith('Everyone') = {text.endswith('Everyone')}")
# =============================================================================
# 6. STRING METHODS - CHECK
# =============================================================================
print("\n--- 6. Check Methods ---\n")
# Different types of strings
alpha = "Hello"
digit = "12345"
alnum = "Hello123"
space = " "
lower = "hello"
upper = "HELLO"
title = "Hello World"
print(f"'{alpha}'.isalpha() = {alpha.isalpha()}")
print(f"'{digit}'.isdigit() = {digit.isdigit()}")
print(f"'{alnum}'.isalnum() = {alnum.isalnum()}")
print(f"'{space}'.isspace() = {space.isspace()}")
print(f"'{lower}'.islower() = {lower.islower()}")
print(f"'{upper}'.isupper() = {upper.isupper()}")
print(f"'{title}'.istitle() = {title.istitle()}")
# =============================================================================
# 7. STRING METHODS - MODIFICATION
# =============================================================================
print("\n--- 7. Modification Methods ---\n")
# Strip
text = " Hello World "
print(f"Original: '{text}'")
print(f"strip(): '{text.strip()}'")
print(f"lstrip(): '{text.lstrip()}'")
print(f"rstrip(): '{text.rstrip()}'")
# Strip specific characters
text2 = "###Hello###"
print(f"\nOriginal: '{text2}'")
print(f"strip('#'): '{text2.strip('#')}'")
# Replace
text3 = "Hello World"
print(f"\nOriginal: '{text3}'")
print(f"replace('World', 'Python'): '{text3.replace('World', 'Python')}'")
print(f"replace('l', 'L'): '{text3.replace('l', 'L')}'")
print(f"replace('l', 'L', 1): '{text3.replace('l', 'L', 1)}'") # Limit to 1
# Split
sentence = "apple,banana,cherry,date"
print(f"\nOriginal: '{sentence}'")
print(f"split(','): {sentence.split(',')}")
words = "Hello World Python"
print(f"Original: '{words}'")
print(f"split(): {words.split()}") # Split by whitespace
# Join
fruits = ['apple', 'banana', 'cherry']
print(f"\nList: {fruits}")
print(f"', '.join(): '{', '.join(fruits)}'")
print(f"'-'.join(): '{'-'.join(fruits)}'")
# =============================================================================
# 8. STRING FORMATTING
# =============================================================================
print("\n--- 8. String Formatting ---\n")
name = "Alice"
age = 25
height = 1.756
balance = 1234567.89
# f-strings (Python 3.6+) - RECOMMENDED
print("f-strings:")
print(f"Name: {name}, Age: {age}")
print(f"Next year: {age + 1}")
print(f"Height: {height:.2f} meters")
# Alignment
print(f"\nAlignment:")
print(f"Right align: '{name:>15}'")
print(f"Left align: '{name:<15}'")
print(f"Center: '{name:^15}'")
print(f"Fill char: '{name:*^15}'")
# Number formatting
print(f"\nNumber formatting:")
print(f"Comma separator: {balance:,.2f}")
print(f"Percentage: {0.756:.1%}")
print(f"Zero-padded: {age:05d}")
# Different bases
num = 255
print(f"\nNumber bases for {num}:")
print(f"Binary: {num:b}")
print(f"Octal: {num:o}")
print(f"Hex (lower): {num:x}")
print(f"Hex (upper): {num:X}")
# format() method
print("\nformat() method:")
print("Name: {}, Age: {}".format(name, age))
print("{0} is {1}, and {0} likes Python".format(name, age))
print("{n} is {a} years old".format(n=name, a=age))
# % operator (old style)
print("\n% operator (old style):")
print("Name: %s, Age: %d" % (name, age))
print("Height: %.2f" % height)
# =============================================================================
# 9. ESCAPE CHARACTERS
# =============================================================================
print("\n--- 9. Escape Characters ---\n")
print("Newline: Hello\\nWorld")
print("Hello\nWorld")
print("\nTab: Hello\\tWorld")
print("Hello\tWorld")
print("\nQuotes: He said \\\"Hi\\\"")
print("He said \"Hi\"")
print("\nBackslash: C:\\\\Users\\\\name")
print("C:\\Users\\name")
# =============================================================================
# 10. RAW STRINGS
# =============================================================================
print("\n--- 10. Raw Strings ---\n")
# Normal string
print("Normal: C:\\new_folder")
# Raw string (prefix with r)
print("Raw: " + r"C:\new_folder")
# Useful for Windows paths
path = r"C:\Users\John\Documents\file.txt"
print(f"Path: {path}")
# Useful for regex patterns
pattern = r"\d+\.\d+"
print(f"Regex pattern: {pattern}")
# =============================================================================
# 11. STRING OPERATIONS
# =============================================================================
print("\n--- 11. String Operations ---\n")
# Concatenation
first = "Hello"
second = "World"
combined = first + " " + second
print(f"Concatenation: '{first}' + ' ' + '{second}' = '{combined}'")
# Repetition
line = "-" * 20
print(f"Repetition: '-' * 20 = '{line}'")
# Membership
text = "Hello World"
print(f"\n'World' in '{text}': {'World' in text}")
print(f"'Python' in '{text}': {'Python' in text}")
# Length
print(f"\nlen('{text}'): {len(text)}")
# Character codes
print(f"\nord('A'): {ord('A')}")
print(f"chr(65): '{chr(65)}'")
# =============================================================================
# 12. REGULAR EXPRESSIONS (INTRO)
# =============================================================================
print("\n--- 12. Regular Expressions (Intro) ---\n")
import re
text = "Contact: john@email.com or call 123-456-7890"
print(f"Text: '{text}'")
# Find phone number
phone_pattern = r'\d{3}-\d{3}-\d{4}'
phone = re.search(phone_pattern, text)
if phone:
print(f"Phone found: {phone.group()}")
# Find email
email_pattern = r'\S+@\S+\.\S+'
email = re.search(email_pattern, text)
if email:
print(f"Email found: {email.group()}")
# Find all numbers
numbers = re.findall(r'\d+', text)
print(f"All numbers: {numbers}")
# Replace
censored = re.sub(r'\d', 'X', text)
print(f"Censored: {censored}")
# =============================================================================
# 13. PRACTICAL EXAMPLES
# =============================================================================
print("\n--- 13. Practical Examples ---\n")
# Example 1: Email validation (simple)
def is_valid_email(email):
return '@' in email and '.' in email.split('@')[-1]
test_emails = ["user@example.com", "invalid", "test@com", "a@b.c"]
for email in test_emails:
print(f"'{email}' valid: {is_valid_email(email)}")
# Example 2: Word counter
sentence = "Python is awesome and Python is fun"
words = sentence.lower().split()
word_count = {}
for word in words:
word_count[word] = word_count.get(word, 0) + 1
print(f"\nWord count: {word_count}")
# Example 3: Palindrome checker
def is_palindrome(s):
s = s.lower().replace(" ", "")
return s == s[::-1]
test_words = ["radar", "Python", "level", "hello"]
print("\nPalindrome check:")
for word in test_words:
print(f"'{word}': {is_palindrome(word)}")
# Example 4: Title case converter
def to_title_case(s):
return ' '.join(word.capitalize() for word in s.split())
text = "hello world from python"
print(f"\nTitle case: '{to_title_case(text)}'")
# Example 5: Remove duplicates from string
def remove_duplicates(s):
result = ""
for char in s:
if char not in result:
result += char
return result
text = "aabbccdd"
print(f"Remove duplicates from '{text}': '{remove_duplicates(text)}'")
print("\n" + "=" * 60)
print("END OF EXAMPLES")
print("=" * 60)