On today's blog, we’ll look at more examples of string manipulation without using any built-in Python methods. The key is to understand the problem and break it down step-by-step.
Problem: Swap Letter Cases
Task
Given a stringinput_string, write a function that transforms all lowercase letters to uppercase and all uppercase letters to lowercase. If the character is not a letter, leave it unchanged.
Understanding the Problem
What we’re asked to do is swap the case of each letter in the string:
-
abecomesA -
Zbecomesz - Non-letter characters remain unchanged
Step-by-Step Breakdown
- Start by creating an empty string to hold the result:
store = ''
- Loop through each character in
input_string:
for char in input_string:
- Use ASCII values to switch cases:
- Lowercase to uppercase →
ord(char) - 32 - Uppercase to lowercase →
ord(char) + 32
- Lowercase to uppercase →
Code Implementation
def solution(input_string):
store = ''
for char in input_string:
if 'a' <= char <= 'z':
store += chr(ord(char) - 32)
elif 'A' <= char <= 'Z':
store += chr(ord(char) + 32)
else:
store += char
return store
Why subtract or add 32?
In the ASCII table, lowercase and uppercase letters are separated by 32. For example,'A'is65and'a'is97→65 + 32 = 97.
Problem: Replace All Occurrences of a Character
Task
Given a stringinput_string, return a new string where all occurrences of characterc1are replaced by characterc2.
Do not use any built-in string methods like.replace()
Understanding the Problem
We simply need to replace every instance of c1 with c2, and leave the rest of the string unchanged.
Step-by-Step Breakdown
- Create an empty string to store the result:
store = ''
- Loop through each character:
- If it's equal to
c1, appendc2to the store. - Otherwise, append the original character.
- If it's equal to
Code Implementation
def replace_character(input_string, c1, c2):
store = ''
for char in input_string:
if char == c1:
store += c2
else:
store += char
return store
That’s it for Part 2!
In Part 3, we’ll step into more advanced problems—like counting character frequencies and tracking patterns in strings—all without built-in methods. Stay tuned!
Top comments (0)