Built-in functions of string

M3-R5.1 · Chapter 5: Sequence Data Types · 9 min read

Built-in functions of string: Python provides a variety of built-in string functions (also called methods) to manipulate and work with strings effectively. Here are some of the most commonly used ones:

    Example:

str=”data structure”

s1= “hello365”

s2= “python”

s3 = ‘4567’

s4 = ‘ ‘

s5= ‘comp34%@’

Function

Description

Example

len( )

Returns the length of a string. It counts every character written in the double quotes eve white spaces also.

>>>print(len(str))

 14

capitalize( )

It returns the exact copy of the string with only the first letter in upper case

          OR

Returns a string with its first character capitalized.

 >>>print(str.capitalize())

  'Data structure'

>>>str=”pYTHON programming”

>>>str.capitalize()

     ”Python programming”

find(sub,start,end)

This function is used to search the first occurrence of the substring in the given string . it returns the index at which the substring starts. It returns-1 if the substring does occure in the string.

>>>str=”mammals”

>>>str.find(“ma”)          Output:     0

>>>str.find(“ma”,2,6)    Output:     3

>>>str.find(“md”,2,6)    Output:     -1

isalnum( )

Returns True if the string contains only letters or digits

It returns False , if the string contains any special character like _,@,#,* etc.

>>> str=Save@Earth”

>>> str.isalnum()     Output: False

>>> str=Save1Earth”

>>> str.isalnum()     Output: True

isalpha( )

Returns True if all characters in the string are alphabetic. otherwise. Returns False

>>>”python”.isalpha()        Output: True

>>>”python23”.isalpha()     Output: False

>>>”python  prog”.isalpha()     Output: False

>>>s1.isalpha( )    Output:False >>>s2.isalpha( )    Output:True >>>s3.isalpha( )     Output:False >>>s4.isalpha( )      Output: False >>>s5.isalpha( )       Output:False

isdigit( )

True if all the characters in the string are digits. False otherwise it Returns False

Returns True if all characters in the string are digits. Otherwise it returns False

>>>s1.isdigit( )        Output:False

 >>>s2.isdigit( )       Output:False

>>>s3.isdigit( )        Output:True

>>>s4.isdigit( )       Output:False

>>>s5.isdigit( )       Output:False

islower( )

Returns the exact copy of the string with all the letters in lowercase

>>>str="Save Earth"

>>>str.lower()

'save earth'

isupper( )

Returns the exact copy of the string with all the letters in uppercase

>>>str="save earth"

>>>str.upper()

'SAVE EARTH'

isspace( )

Returns True if there are only whitespace characters in the string. False otherwise

>>> " ".isspace() Output :True

 >>> "".isspace()  Output: False

islower( )

Returns True if all the characters in the string are lowercase. False otherwise.

>>> s1.islower()   Output :True

 >>> s3.islower()    Output :False

supper( )

                             Returns True if all the characters in the string are uppercase. False otherwise.

>>> s1.isupper()    Output :False

 >>> s2.isupper()   Output :False

rstrip( )

Returns a string after removing the trailing characters. (Right side).

 if used without any argument, it removes the trailing whitespaces.

>>> str.rstrip('eur') 'data struct'

>>> str.rstrip('rut')

 'data structure'

>>> str.rstrip('tucers')       'data '

lstrip( )

Returns a string after removing the leading characters. (Left side). if used without any argument, it removes the leading whitespaces

>>> str.lstrip('tad') ' structure'

lstrip( )

Returns True if the string is title cased (First Character of every word capital) . otherwise returns, False

>>> str=”I  Love Python”

>>> str.istitle()  Output: True

Replace(old,new)

The function replaces all the occurrences of the old stsring with the new string.

>>>str=”January  February  March’

>>> str.replace(“uary “ , “ . “)

Output: jan.  Febr.  March

>>> str=”hello”

>>> print str.replace(“ll”,”%”)

 He%%o

>>>str=”Jan Feb March’

>>> str.replace(“ “ , “ - “)

Output: jan-Feb-March

Join()

Returns a string in which the sequence (list, tuple,string) have been joined by separator.

>>>str1=(“jan”,”feb”,”mar”)

>>> str=”&”

>>> str.join(str1)

Output:jan&feb&mar

Swapcase()

Returns the string with case changes.

>>> str=”UPPER”

>>> print str.swapcase()

         Upper

  String Manipulation

Q : Write a program to count frequency of a character in a String

str=input("plz enter any string")

c=input("Enter character to check frequency:")

count=0

for i in str: 

    if i==c:

        count=count+1

print(c,"Occures",count,"time(s).")

Q : Write a program to Count the number of vowels in a string

str = "Hello World"

vowels = "aeiouAEIOU"

count = 0

for char in str:

    if char in vowels:

        count += 1

print("Number of vowels:", count)

Q : Write a program to print the reverse of a String

str = "prakash"

revstr = str[::-1]

print("Reversed string:", revstr)

Q : Write a program to Check if a string is a palindrome or not

s = "madam"

if s == s[::-1]:

    print("Palindrome")

else:

    print("Not a palindrome")

Q : Write a program to Remove all vowels from a string

str = "Beautiful Day"

vowels = "aeiouAEIOU"

newstr= ""

for char in str:

    if char not in vowels:

        newstr = newstr +char

print("Without vowels:", newstr)

Q : Write a program to Remove duplicate characters from a string

str = "programming"

result = ""

for char in str:

    if char not in result:

        result += char

print("After removing duplicates:", result)

Q : Write a program to Count words in a sentence

sentence = "Python is easy to learn"

words = sentence.split()

print("Number of words:", len(words))

Q: Write A Program To Find The Length Of String Without Len()

str=input("enter a string:")

count=0

for c in str:

    count=count+1

print("total number of character :",count

Q : Write a program that counts total character in a string

str=input("enter a string:")

count=0

for c in str:

    if c.isspace()!=True:

        count=count+1

print("total number of character :",count)

Q: Write a program to input name and print each character with a single space

str=input("enter a string:")

i=0

while i<len(str):

    ch=str[i]

    print(ch,end=" ")

    i=i+1

Q: Write a program to reads a string and capitalizes every alternamte letter in it

str=input("enter a string:")

l=len(str)

str1=""

for i in range(0,l):

    if i%2==0:

        str1=str1+str[i]

    else:

        str1=str1+str[i].upper()

print(str1)

Q : Write a program to replace all vowels in a string with *

str=input("plz enter any string")

for i in str:

    if i in "aeiouAEIOU": 

        print("*",end="")

    else:

        print(i,end="")

Q2. Write a program which replaces all vowels in the string with '*'.

string = input("Enter a string :-")

newstring = ""

for i in string :

    if i == "a"or i == "e"or i == "i"or i == "o"or i == "u"or i == "A"or i == "E"or i == "I"or i == "O"or i == "U":

        newstring += "*"

    else :

        newstring += i

print(newstring)

Q: Write a program that read a line and prints no. of lowecase , uppercase letters and digits

line=input("enter a string:")

lo=upp=dig=0

for i in line:

    if (i.islower()):

        lo=lo+1

    elif (i.isupper()):

        upp=upp+1

    elif (i.isdigit()):

        dig=dig+1

print("Total Number of Lower leter :",lo)

print("Total Number of Upper leter :",upp)

print("Total Number of digit :",dig)

Q : Write a program that counts alphabets,digits and special characters in a string

str=input("enter a string:")

alpha=digits=special=0

for i in range(len(str)):

    if (str[i].isalpha()):

        alpha=alpha+1

    elif (str[i].isdigit()):

        digits=digits+1

    else:

        special=special+1

print("Total Number of alphabets in thes string :",alpha)

print("Total Number of digits in thes string :",digits)

print("Total Number of Special Character in the string :",special)