Programs Using Strings

To find a element in the array, find keyword is used. It returns a integer value either if it is found or not. We can use certain conditions like found the element which starts a letter with “C”. For this type of statements it returns a boolean value either True or False.

>>> s = ” He started to learn python “

>>> s.find(“to”)

3

>>> s.find(“and”)

-1

It returned a negative binary value because the array does not have element “and”.

>>> s.endswith(“python”)

True

>>> s.startswith(“He”)

True

Palindrome

Palindrome will compare the string and the corresponding reversed string. If two strings are same the it is said to be palindrome. “Madam” is a palindrome. The below program is to check whether the entered string is palindrome or not.

>>> s = input(” Enter the string “)

for c in s:

z = z + c

if(s == z):

print(” Palindrome “)

else:

print(” Not a Palindrome “)

Output will be :-

Enter the string MADAM

Palindrome

To find number of words in String

>>> s = input(” Enter the line : “)

>>> print(” Number of words is ” % (len(s.split(” “)))

Output :-

Enter the line : He started to learn python

5

To iterate each element in String

>>> s = input(” Enter the string “)

>>> for c in s:

… print(c)

Output :-

Enter the string : python

p

y

t

h

o

n

Leave a comment