Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

DEV Community

Peter Muthama
Peter Muthama

Posted on

String manipulation without in built methods Part 3

In today's post, we dive into more exercises focused on string manipulation without using any built-in methods in Python.


Problem One: Swap Adjacent Characters

Task:

You are given a string s. Your task is to write a function that returns a string in which every pair of adjacent characters in the original string is swapped.

If the string has an odd length, leave the last character as it is.


Explanation

Imagine you're given "abcdef" — the goal is to swap every adjacent character:

  • Swap a and b, then c and d, then e and f → Result: "badcfe"

Now if the string has an odd length, like "hello", you’d swap h and e, then l and l, and leave o untouched → Result: "ehllo"


Steps:

  • Convert the string into a list to easily swap characters.
  • Loop through it with a step of 2 and swap char_list[i] and char_list[i+1].
  • Join the result back into a string manually.
def solution(s):
    char_list = list(s)

    for i in range(0, len(char_list) - 1, 2):
        char_list[i], char_list[i + 1] = char_list[i + 1], char_list[i]

    results = ""
    for char in char_list:
        results += char
    return results
Enter fullscreen mode Exit fullscreen mode

Problem Two: Palindrome Check (No Built-ins)

Task:

Write a function that checks whether a string is a palindrome.

  • Case should be ignored (e.g. A == a)
  • Non-letter characters should be ignored
  • Do not use any built-in string methods (like .lower())

Explanation

We’re going to:

  • Filter only alphabet characters from the string.
  • Convert any uppercase letters to lowercase manually using ASCII math.
  • Then use a two-pointer technique to check if the string reads the same forward and backward.

Steps:

  • Loop through each character and keep only letters.
  • Convert uppercase to lowercase by adding 32 to the ASCII value.
  • Compare characters from both ends inward.
def solution(input_string):
    filtered_char = []

    for char in input_string:
        if ('a' <= char <= 'z') or ('A' <= char <= 'Z'):
            if 'A' <= char <= 'Z':
                filtered_char.append(chr(ord(char) + 32))
            else:
                filtered_char.append(char)

    left = 0
    right = len(filtered_char) - 1

    while left < right:
        if filtered_char[left] != filtered_char[right]:
            return False
        left += 1
        right -= 1

    return True
Enter fullscreen mode Exit fullscreen mode

That's all for today's string manipulation exercises without built-in methods. Keep practicing - repetition and raw logic will sharpen your coding instincts!

Top comments (0)