STRING INDEXING NOTES COMMENTED
# String Indexing and Special Character Handling
# 1. Basic String Indexing
my_string = "Hello, World!"
print(my_string[0]) # Prints 'H' (first character)
print(my_string[-1]) # Prints '!' (last character)
print(my_string[7]) # Prints 'W' (8th character, remember
indexing starts at 0)
# 2. String Slicing
print(my_string[0:5]) # Prints 'Hello' (characters from index
0 to 4)
print(my_string[7:]) # Prints 'World!' (characters from index
7 to the end)
print(my_string[:5]) # Prints 'Hello' (characters from start
to index 4)
print(my_string[::2]) # Prints 'Hlo ol!' (every second
character)
# 3. Reverse String
print(my_string[::-1]) # Prints '!dlroW ,olleH' (reverses the
string)
# 4. String Length
print(len(my_string)) # Prints 13 (length of the string)
# 5. Ignoring Special Characters
import re # Import regular expression module
text = "Hello, World! 123 @#$%"
clean_text = re.sub(r'[^a-zA-Z0-9\s]', '', text) # Remove all
special characters
print(clean_text) # Prints 'Hello World 123'
# 6. Ignoring Specific Special Characters
special_chars = r'~!@#$%^&*()_+-=[]{}\|:";\'<>?,./'
translation_table = str.maketrans("", "", special_chars) #
Create a translation table
clean_text = text.translate(translation_table) # Remove
specified special characters
print(clean_text) # Prints 'Hello World 123 '
# 7. Keeping Only Alphanumeric Characters
alphanumeric_only = ''.join(char for char in text if
char.isalnum()) # Keep only alphanumeric characters
print(alphanumeric_only) # Prints 'HelloWorld123'
# 8. Replacing Special Characters (see below)
replaced_text = re.sub(r'[^\w\s]', '_', text) # Replace
special characters with underscore
replaced_text = re.sub(r'[^\w\s]', '_', text) # Replace
special characters with underscore
print(replaced_text) # Prints 'Hello_ World_ 123 ___'
# 9. Counting Occurrences of a Character
char_count = text.count('o') # Count occurrences of 'o'
print(char_count) # Prints 2
# 10. Finding Index of a Substring
index = text.find('World') # Find the starting index of
'World'
print(index) # Prints 7
# 11. Splitting a String
words = text.split() # Split the string into a list of words
print(words) # Prints ['Hello,', 'World!', '123', '@#$%']
# 12. Joining Strings
joined_text = ' '.join(words) # Join the list of words back
into a string
print(joined_text) # Prints 'Hello, World! 123 @#$%'
# 13. Checking String Start and End
print(text.startswith('Hello')) # Prints True (checks if
string starts with 'Hello')
print(text.endswith('123')) # Prints False (checks if string
ends with '123')
# 14. Changing Case
print(text.upper()) # Prints 'HELLO, WORLD! 123 @#$%' (all
uppercase)
print(text.lower()) # Prints 'hello, world! 123 @#$%' (all
lowercase)
print(text.title()) # Prints 'Hello, World! 123 @#$%'
(capitalize first letter of each word)
# 15. Stripping Whitespace
padded_text = " Hello, World! "
print(padded_text.strip()) # Prints 'Hello, World!' (removes
leading and trailing whitespace)
print(padded_text.lstrip()) # Prints 'Hello, World! '
(removes leading whitespace)
print(padded_text.rstrip()) # Prints ' Hello, World!'
(removes trailing whitespace)
# 16. Replacing Substrings
print(text.replace('World', 'Python')) # Prints 'Hello,
Python! 123 @#$%'
# 17. Checking String Content
print(text.isalpha()) # Prints False (checks if all
characters are alphabetic)
print(text.isalpha()) # Prints False (checks if all
characters are alphabetic)
print(text.isdigit()) # Prints False (checks if all
characters are digits)
print(text.isalnum()) # Prints False (checks if all
characters are alphanumeric)
# 18. Formatting Strings
name = "Alice"
age = 30
formatted_string = f"My name is {name} and I am {age} years
old." # f-string formatting
print(formatted_string) # Prints 'My name is Alice and I am
30 years old.'
# 19. Raw Strings
raw_string = r"This is a raw string\n" # Treats backslashes
as literal characters
print(raw_string) # Prints 'This is a raw string\n'
# 20. Multiline Strings
multiline = """This is a
multiline string
with line breaks."""
print(multiline) # Prints the multiline string as is
# Sample report for testing
report = "!@#$%^&*()_+-=[]}{\|:'<>?,./"
# 1. Handling Tilde (~)
tilde_removed = report.replace('~', '') # Remove tilde
print(tilde_removed) # Output: same as report (no tilde in
original string)
# 2. Handling Exclamation Mark (!)
exclamation_removed = report.replace('!', '') # Remove
exclamation mark
print(exclamation_removed)
# 3. Handling At Symbol (@)
at_symbol_removed = report.replace('@', '') # Remove at
symbol
print(at_symbol_removed)
# 4. Handling Hash (#)
hash_removed = report.replace('#', '') # Remove hash
print(hash_removed)
# 5. Handling Dollar Sign ($)
dollar_sign_removed = report.replace('$', '') # Remove dollar
sign
print(dollar_sign_removed)
# 6. Handling Percent Sign (%)
percent_sign_removed = report.replace('%', '') # Remove
percent sign
print(percent_sign_removed)
# 7. Handling Caret (^)
caret_removed = report.replace('^', '') # Remove caret
print(caret_removed)
# 8. Handling Ampersand (&)
ampersand_removed = report.replace('&', '') # Remove
ampersand
print(ampersand_removed)
# 9. Handling Asterisk (*)
asterisk_removed = report.replace('*', '') # Remove asterisk
print(asterisk_removed)
# 10. Handling Parentheses (())
parentheses_removed = report.replace('(', '').replace(')', '')
# Remove parentheses
print(parentheses_removed)
# 11. Handling Underscore (_)
underscore_removed = report.replace('_', '') # Remove
underscore
print(underscore_removed)
# 12. Handling Plus Sign (+)
plus_sign_removed = report.replace('+', '') # Remove plus
sign
print(plus_sign_removed)
# 13. Handling Hyphen (-)
hyphen_removed = report.replace('-', '') # Remove hyphen
print(hyphen_removed)
# 14. Handling Equal Sign (=)
equal_sign_removed = report.replace('=', '') # Remove equal
sign
print(equal_sign_removed)
# 15. Handling Square Brackets ([])
square_brackets_removed = report.replace('[', '').replace(']',
'') # Remove square brackets
print(square_brackets_removed)
# 16. Handling Curly Braces ({})
curly_braces_removed = report.replace('{', '').replace('}',
'') # Remove curly braces
print(curly_braces_removed)
# 17. Handling Backslash (\)
backslash_removed = report.replace('\\', '') # Remove
backslash
print(backslash_removed)
# 18. Handling Vertical Bar (|)
vertical_bar_removed = report.replace('|', '') # Remove
vertical bar
print(vertical_bar_removed)
# 19. Handling Colon (:)
colon_removed = report.replace(':', '') # Remove colon
print(colon_removed)
# 20. Handling Semicolon (;)
semicolon_removed = report.replace(';', '') # Remove
semicolon
print(semicolon_removed)
# 21. Handling Double Quotes (")
double_quotes_removed = report.replace('"', '') # Remove
double quotes
print(double_quotes_removed)
# 22. Handling Single Quote (')
single_quote_removed = report.replace("'", '') # Remove
single quote
print(single_quote_removed)
# 23. Handling Less Than (<)
less_than_removed = report.replace('<', '') # Remove less
than sign
print(less_than_removed)
# 24. Handling Greater Than (>)
greater_than_removed = report.replace('>', '') # Remove
greater than sign
print(greater_than_removed)
# 25. Handling Question Mark (?)
question_mark_removed = report.replace('?', '') # Remove
question mark
print(question_mark_removed)
# 26. Handling Comma (,)
comma_removed = report.replace(',', '') # Remove comma
print(comma_removed)
# 27. Handling Period (.)
period_removed = report.replace('.', '') # Remove period
print(period_removed)
# 28. Handling Forward Slash (/)
forward_slash_removed = report.replace('/', '') # Remove
forward slash
print(forward_slash_removed)