Computer Science, asked by shifahaneef2880, 9 months ago

write a program to accept a string from user and replace all single a with an

Answers

Answered by fiercespartan
5

We need to replace single 'a'.

For example, if we have a string 'apple', we should not replace the 'a' in apple. But if we have a sentence like:

'an apple a day', we need to change the single 'a' to 'an'

I can think of 2 ways to solve this.

WAY #1 :

If we think about this in a different way, we have to replace the 'a' with spaces on both the sides. To be clear, we need to replace ' a ' with a ' an '. Notice that there are spaces. if we just replace 'a', it would replace even the 'a' in the apple and we do not want that.

To replace an character in a string, we use .replace()

The syntax to .replace is simple,

string.replace(x , y)

x is the character we want to replace and y is the character we want to replace x with.

CODE #1:

sentence = input().replace(' a ',' an ')

print(sentence)

WAY #2:

We split the sentence and we transverse through the list, check for 'a' and if it is 'a' we change the 'a' to an 'an'.

CODE #2:

sentence = input().split()

for i in range(len(sentence)):

if sentence[i] == 'a':

 sentence[i] == 'an'

sentence = ' '.join(sentence)

print(sentence)

Similar questions