DEV Community

Cover image for python string
Keerthana M
Keerthana M

Posted on

python string

Task1:

To remove the front space before the sentence.

sentence = '                 today is friday'
space = ' '
front_space = True
for letter in sentence:
    if letter == space and front_space == True:
        continue
    else:
        front_space = False
        print(letter, end='')

Enter fullscreen mode Exit fullscreen mode

OUTPUT:
today is friday

Task 2:

To remove the back space from the sentence

sentence = 'today is friday                  '
back_space = False
for letter in sentence:
    if letter == ' ' and back_space == False:
        continue
    else:
        back_space = True
        print(letter,end='')

Enter fullscreen mode Exit fullscreen mode

OUTPUT:
today is friday

TASK3:

To remove the unwanted spaces from the sentence
sentence = 'today is friday'
output: today is friday

sentence = 'today           is                    friday'
previous_letter = True 
for letter in sentence:
    if letter != ' ':
        print(letter, end='') 
        previous_letter = True 
    else:
        if letter == ' ' and previous_letter == True:
            print(letter,end='')
            previous_letter = False
Enter fullscreen mode Exit fullscreen mode

*output: *
today is friday

Task4:

To find a word from an sentence

name = 'mahendra singh dhoni'
key = 'mahendra'
start = 0
end = len(key)
while end < len(name):
    if name[start:end] == key:
        print('Key is present at position',start)
        break
    start+=1
    end+=1
else:
    print('Key is not found')
Enter fullscreen mode Exit fullscreen mode

OUTPUT:
Key is present at position 0

name = 'mahendra singh dhoni'
key = 'singh'
start = 0
end = len(key)
while end < len(name):
    if name[start:end] == key:
        print('Key is present at position',start)
        break
    start+=1
    end+=1
else:
    print('Key is not found')
Enter fullscreen mode Exit fullscreen mode

OUTPUT:
Key is present at position 9

name = 'mahendra singh dhoni'
key = 'dhoni'
start = 0
end = len(key)
while end <= len(name):
if name[start:end] == key:
print('Key is present at position',start)
break
start+=1
end+=1
else:
print('Key is not found')

OUTPUT:
Key is present at position 15

Top comments (0)