|
| 1 | +# String Operations in Python - Notes by Ali Haider |
| 2 | + |
| 3 | +# Basic string assignment and slicing |
| 4 | +name = 'Ali Haider' |
| 5 | +print(name) |
| 6 | + |
| 7 | +nam = name[0:4] # Includes index 0 to 3; does NOT include index 4 |
| 8 | +print(nam) |
| 9 | + |
| 10 | +ended = name[-1] # Negative index starts from the end (-1 = last character) |
| 11 | +print(ended) |
| 12 | + |
| 13 | +# Slicing a string of digits |
| 14 | +number = '0123456789' |
| 15 | +print(number[:]) # Prints the whole string |
| 16 | +print(number[3:]) # From index 3 to the end |
| 17 | +print(number[:3]) # From start to index 2 (3 not included) |
| 18 | +print(number[0:9:3]) # From 0 to 9, skipping every 3rd character |
| 19 | + |
| 20 | +# Case conversion |
| 21 | +print(name.upper()) # Converts to uppercase |
| 22 | +print(name.lower()) # Converts to lowercase |
| 23 | + |
| 24 | +# Trimming and replacing |
| 25 | +brother_name = ' Ali Husnain ' |
| 26 | +print(brother_name) |
| 27 | +print(brother_name.strip()) # Removes spaces from both ends |
| 28 | +print(brother_name.replace('Ali', 'Okokk')) # Replaces 'Ali' with 'Okokk' |
| 29 | + |
| 30 | +# String to list |
| 31 | +hobbies = 'eating, dancing, planting, drawing' |
| 32 | +print(hobbies.split(', ')) # Splits string into list using comma+space |
| 33 | + |
| 34 | +# Finding and counting substrings |
| 35 | +print(hobbies.find('dancing')) # Returns index of 'dancing', -1 if not found |
| 36 | +print(len(hobbies)) # Length of string |
| 37 | +boss = 'ali haider is my brother brother' |
| 38 | +print(boss.count('brother')) # Counts how many times 'brother' appears |
| 39 | + |
| 40 | +# String formatting |
| 41 | +quantity = 2 |
| 42 | +fruit = 'apple' |
| 43 | +order = 'You have ordered {} number of {}' |
| 44 | +print(order.format(fruit, quantity)) # Inserts variables into string |
| 45 | + |
| 46 | +# Joining lists into strings |
| 47 | +HobbyList = ['drawing', 'boating', 'dancing'] |
| 48 | +print(' '.join(HobbyList)) # Joins with space |
| 49 | +print('-'.join(HobbyList)) # Joins with hyphen (like a URL slug) |
| 50 | + |
| 51 | +# Looping over string |
| 52 | +for character in boss: |
| 53 | + print(character) |
| 54 | + |
| 55 | +# Length and escape characters |
| 56 | +print(len(boss)) |
| 57 | +print("He said, \"I am here to help you\"") # Escape quotes with \" |
| 58 | +print(r'user\ali\id') # Raw string to print backslashes as-is |
| 59 | + |
| 60 | +# Membership test |
| 61 | +print('brother' in boss) # Checks if 'brother' exists in string (True/False) |
0 commit comments