Strings in Python
Master string handling in Python: single-line/multi-line strings, f-strings, indexing, traversal, searching, slicing, comparison, replacing, Unicode conversions, and more.
Creating Strings
A string is a sequence of characters. In Python, strings can be created using single quotes, double quotes, or triple quotes for multi-line strings.
1. Single Line Strings
Single-line strings can use single or double quotes.
2. Multi-line Strings
Use triple quotes for multi-line strings.
3. f-Strings (String Interpolation)
Insert variables inside strings using f-strings.
String Basics (Indexing, Length, Traversal)
Strings behave like sequences. You can access characters using indexes and get length using len().
1. Access Character by Index
Use str[index]. Index starts from 0.
2. Getting String Length
Use len() to get number of characters.
3. Traversing Through a String
Loop through each character using for loop.
Formatted Output
You can align text for tables using string methods like ljust() and rjust().
1. Formatted Table Output
Align columns like a table.
Comparing & Concatenating Strings
Strings can be compared using == and joined using + or f-strings.
1. Comparing Strings
Use == for equality.
2. Concatenating Strings
Use + or f-strings.
String Transformations
Transformations modify or process string values.
1. Reverse a String
Use slicing.
2. Change Case
Use upper() and lower().
3. Repeat a String
Use multiplication operator.
Unicode Conversions
Python uses Unicode. Use ord() and chr() for conversions.
1. Character to Code
Use ord().
2. Code to Character
Use chr().
Slicing, Splitting & Trimming
These operations are common in parsing and validation.
1. Slicing
Use string slicing syntax.
2. Split String
Use split().
3. Trimming Whitespace
Use strip(), lstrip(), rstrip(). Pipes (|) in the output show where the string starts and ends so you can see the effect of trimming.
Searching & Replacing
Use in, find(), and replace() for searching and replacing.
1. Check if String Contains Substring
Use "in" operator.
2. Replace Text
Use replace().
3. Find Index of Substring
Use find().
4. Startswith & Endswith
Check prefix and suffix.