DEV Community

Vasanthakumari N
Vasanthakumari N

Posted on

Python Day 25: String Operations Using While Loop

1. Capitalize the First Letter of Every Word

Task: Convert the first letter of every word into an uppercase letter.

sen ='today is sunday'
print(sen[0].upper(),end='')
i = 1
while i < len(sen):

    if sen[i] == ' ':
        print(sen[i], end='')
        print(sen[i+1].upper(),end='')
        i+=1
    else:
        print(sen[i],end='')
    i+=1
Enter fullscreen mode Exit fullscreen mode
Output:

Today Is Sunday
Enter fullscreen mode Exit fullscreen mode

Explanation:

  • sen[0].upper() converts the first character into uppercase.
  • The while loop checks the remaining characters.
  • When a space is found, the next character is converted into uppercase.
  • end='' prints everything on the same line.

2. Add a Space Before Every Uppercase Letter

Task: Identify uppercase letters and add a space before them, except for the first character.

name = 'AjayKarthikeyan'
print(name[0], end='')
i = 1
while i < len(name):
    if name[i] >= 'A' and name[i] <= 'Z':  
        print(' ' + name[i],end='')
    else:
        print(name[i],end='')
    i+=1
Enter fullscreen mode Exit fullscreen mode
Output:

Ajay Karthikeyan
Enter fullscreen mode Exit fullscreen mode

Explanation:

  • We print the first character separately.
  • The loop starts from index 1.
  • The condition checks whether the current character is between A and Z.
  • If it is uppercase, a space is printed before it.
  • Otherwise, the character is printed normally.

3. Replace a Word in a String

Task: Replace Hello with Hi.

name = "Hello Prem! How are you? Hello"

l = name.split(' ')
print(l)
i = 0 
while i < len(l):
    if l[i] == 'Hello':
        l[i] = 'Hi'
    i+=1
else:
    name = ' '.join(l)
    print(name)
Enter fullscreen mode Exit fullscreen mode
Output:

['Hello', 'Prem!', 'How', 'are', 'you?', 'Hello']
Hi Prem! How are you? Hi
Enter fullscreen mode Exit fullscreen mode

Explanation:

First, we use split() to convert the string into a list of words.

l = name.split(' ')

Next, the while loop checks every list element.

if l[i] == 'Hello':
l[i] = 'Hi'

Whenever the word Hello is found, it is replaced with Hi.

Finally, we use join() to convert the list back into a string.

name = ' '.join(l)

4. Remove Unwanted Spaces at the Beginning

Task: Remove spaces from the beginning of a string.

name = "               How are you?"
first_space = True
i = 0 
while i < len(name):
    if name[i] == ' ' and first_space == True:
        pass
    else:
        print(name[i],end='')
        first_space = False
    i+=1
Enter fullscreen mode Exit fullscreen mode

Output:

How are you?
Enter fullscreen mode Exit fullscreen mode

Explanation:

  • first_space = True indicates that we are checking spaces at the beginning.
  • The loop starts from index 0.
  • If the current character is a space and first_space is True, pass skips printing it.
  • Once a non-space character is found, it is printed.
  • first_space = False ensures that spaces between words are not removed.

Here, pass does nothing. It simply allows the loop to continue without printing the character.

5. Remove Unwanted Spaces at the End

Task: Remove spaces from the end of a string.

name = "How are you?         "
last_space = True
i = len(name)-1 
while i >= 0:
    if name[i] == ' ' and last_space == True:
        pass
    else:
       last_space = False
       print(name[:i+1])
       break
    i-=1
Enter fullscreen mode Exit fullscreen mode
Output:

How are you?
Enter fullscreen mode Exit fullscreen mode

Explanation:

  • len(name) - 1 gives the last index of the string.
  • The loop starts from the last character and moves backwards.
  • If the character is a space, we decrease the index.
  • When a non-space character is found, we print the string up to that position.
  • break stops the loop.

Understanding slicing

name[:i+1]

The ending index in slicing is excluded. Therefore, we use i + 1 to include the last required character.

6. Remove Extra Spaces Between Words

Task: Convert multiple spaces between words into a single space.

name = "How                            are              you?"
#How are you
i = 0
while i < len(name):
    if name[i] != ' ':
        print(name[i],end='')
    else:
        if name[i+1] != ' ':
            print(name[i],end='')  
    i+=1
Enter fullscreen mode Exit fullscreen mode

Output:

How are you?
Enter fullscreen mode Exit fullscreen mode

Explanation:

  • If the current character is not a space, print it.
  • If it is a space, check the next character.
  • If the next character is not a space, print the current space.
  • Otherwise, skip the extra spaces.

Practice Tasks and Solutions

Task 1: Remove All Spaces Between Words

Input:

sen = 'Ajay Karthikeyan'

Expected output:

AjayKarthikeyan

Solution using while loop

sen = 'Ajay Karthikeyan'

i = 0

while i < len(sen):
    if sen[i] != ' ':
        print(sen[i], end='')

    i += 1
Enter fullscreen mode Exit fullscreen mode

Explanation:

  • The loop checks every character.
  • If the character is not a space, it gets printed.
  • If it is a space, it is skipped.

Task 2: Reverse the Order of Words Using a List

Input:

sen = 'Today Is Sunday'

Expected output:

Sunday Is Today

Solution

sen = 'Today Is Sunday'

words = sen.split(' ')

i = len(words) - 1

while i >= 0:
    print(words[i], end=' ')

    i -= 1
Enter fullscreen mode Exit fullscreen mode

Output:

Sunday Is Today
Enter fullscreen mode Exit fullscreen mode

Explanation:

  • split() converts the sentence into a list.
  • We start from the last index of the list.
  • The loop prints each word in reverse order.
  • i -= 1 moves towards the first word.

Task 3: Reverse the Order of Words Without Using a List

We can also reverse the word order without converting the sentence into a list.

Solution using while loop

sen = 'Today Is Sunday'

i = len(sen) - 1

while i >= 0:

    while i >= 0 and sen[i] == ' ':
        i -= 1

    end = i

    while i >= 0 and sen[i] != ' ':
        i -= 1

    print(sen[i+1:end+1], end=' ')
Enter fullscreen mode Exit fullscreen mode
Output:

Sunday Is Today
Enter fullscreen mode Exit fullscreen mode

Explanation:

We use two while loops:

  • The first loop skips spaces while moving backwards.
  • The second loop finds the beginning of the current word.
  • String slicing extracts the word.
  • The outer loop continues until all words are printed.

Unlike the previous solution, this approach does not use split() or a list.

Task 4: Count the Number of Vowels in a String

Input:

sen = 'Today Is Sunday'

Expected output:

Number of Vowels: 5

Solution


sen = 'Today Is Sunday'

vowel_count = 0
i = 0

while i < len(sen):

    if sen[i].lower() == 'a' or sen[i].lower() == 'e' or sen[i].lower() == 'i' or sen[i].lower() == 'o' or sen[i].lower() == 'u':
        vowel_count += 1

    i += 1

print("Number of Vowels:", vowel_count)
Enter fullscreen mode Exit fullscreen mode
Output:

Number of Vowels: 5
Enter fullscreen mode Exit fullscreen mode

Explanation:

  • vowel_count = 0 initializes the counter.
  • The loop checks every character in the string.
  • lower() converts uppercase vowels into lowercase.
  • If the character is a vowel, the counter increases.
  • Finally, we print the total number of vowels.

For Today Is Sunday, the vowels are o, a, I, u, and a. So the count is 5.

Top comments (0)