Strings are IMMUTABLE sequences of Unicode characters.
s = 'Hello, World!'
print(len(s)) # 13
# Indexing
# P Y T H O N
# 0 1 2 3 4 5 (positive)
# -6 -5 -4 -3 -2 -1 (negative)
print(s[0]) # 'P'
print(s[-1]) # '!'
# Slicing: s[start:stop:step]
print(s[0:3]) # 'Hel'
print(s[::-1]) # '!dlroW ,olleH' (reversed)
print(s[::2]) # 'Hlo ol!'text = 'Python is awesome'
words = text.split() # ['Python', 'is', 'awesome']
csv = 'a,b,c,d'
parts = csv.split(',') # ['a', 'b', 'c', 'd']
# Join (called on the SEPARATOR string)
result = ' '.join(words) # 'Python is awesome'
result = '-'.join(parts) # 'a-b-c-d'
path = '/'.join(['home', 'user', 'file.txt']) # 'home/user/file.txt's = 'Hello, World!'
print(s.find('World')) # 7 (-1 if not found)
print(s.index('World')) # 7 (ValueError if not found)
print(s.count('l')) # 3
print(s.startswith('Hello')) # True
print(s.endswith('!')) # True
# Character type checks
print('123'.isdigit()) # True
print('abc'.isalpha()) # True
print('abc123'.isalnum()) # Trues = ' Hello, World! '
print(s.strip()) # 'Hello, World!'
print(s.upper()) # ' HELLO, WORLD! '
print(s.lower()) # ' hello, world! '
print(s.replace('World', 'Python')) # ' Hello, Python! '# Palindrome check
def is_palindrome(s):
s = s.lower().replace(' ', '')
return s == s[::-1]
print(is_palindrome('racecar')) # True
print(is_palindrome('A man a plan a canal Panama')) # True
# Anagram check
def is_anagram(s1, s2):
return sorted(s1.replace(' ', '').lower()) == sorted(s2.replace(' ', '').lower())
print(is_anagram('listen', 'silent')) # True
# Reverse words in a string
def reverse_words(s):
return ' '.join(s.split()[::-1])
print(reverse_words('Hello World Python')) # 'Python World Hello'Create three string utility functions: 1) `is_palindrome(s)` — check if a string is a palindrome (ignore case and spaces). 2) `count_vowels(s)` — return total count of a,e,i,o,u (case-insensitive). 3) `compress_string(s)` — compress consecutive characters (e.g., 'aaabbbcc' → 'a3b3c2', 'abcd' → 'a1b1c1d1').