Strings in Python
Learn strings in python for DSA

In Python, strings are immutable.
This means once a string is created, it cannot be changed.
Example:
s = "python"
s[0] = "P" # ❌ This will give an error
You cannot modify a character directly inside a string.
What Does “Immutable” Mean?
If you try to change a string, Python does not modify the original string.
Instead, it creates a new string in memory.
Example:
s = "python"
s = "Python"
Here, a new string is created.
Some of the most common and useful string methods are:
Case Conversion: upper(), lower(), capitalize(), title(), and swapcase() allow for changing the casing of strings.
Searching: Methods like find(), index(), and count() locate or count substrings, while startswith() and endswith() check string boundaries.
Modification: strip() (and lstrip()/rstrip()) removes whitespace, replace() substitutes substrings, split() divides strings into lists, and join() concatenates iterables.
Formatting/Validation: format() or f-strings are used for string formatting, while isalpha(), isdigit(), and isalnum() validate string content.
Why Is This Important in DSA?
Many interview problems are based on strings:
Palindrome problems
Anagram checking
Substring problems
Pattern matching
Sliding window on strings
Because strings are immutable:
You cannot modify characters directly.
You often convert strings into lists when modification is required.
Example:
s = "python"
s_list = list(s)
s_list[0] = "P"
s = "".join(s_list)
Searching in a String → O(N)
You can check whether a character exists in a string using:
if "a" in s:
print(True)
This operation takes O(N) time because Python may need to traverse the entire string.
Time Complexity :
Index access → O(1)
Searching → O(N)
Concatenation inside a loop → Can become O(N²) (be careful!)
For large string manipulation problems, consider:
Using a list for modification
Using
join()instead of repeated concatenation






