0% found this document useful (0 votes)
3 views12 pages

String Functions

The document provides a comprehensive overview of various string functions in Python, including methods for checking character types (e.g., isalpha, isdigit), manipulating case (e.g., lower, upper, capitalize), and modifying strings (e.g., replace, strip). It also includes examples demonstrating the usage of these functions and their expected outputs. Additionally, it presents programming questions that involve string manipulation tasks.

Uploaded by

Shuomik Roy
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views12 pages

String Functions

The document provides a comprehensive overview of various string functions in Python, including methods for checking character types (e.g., isalpha, isdigit), manipulating case (e.g., lower, upper, capitalize), and modifying strings (e.g., replace, strip). It also includes examples demonstrating the usage of these functions and their expected outputs. Additionally, it presents programming questions that involve string manipulation tasks.

Uploaded by

Shuomik Roy
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 12

STRING FUNCTIONS

len()
--> Return the length of characters present in the string

In [1]: s = "ABCD"
print(len(s))

In [2]: s = " I love Programming "


print(len(s))

20

isalpha()
-> Checks whether all the characters of the string are letters or not

In [4]: s = "ABCD"
s.isalpha()

Out[4]: True

In [5]: s = "123"
s.isalpha()

Out[5]: False

In [6]: s = "ABCD123"
s.isalpha()

Out[6]: False

isdigit()
-> Checks whether all the character of the string are digit or not

In [7]: s = "ABCD"
s.isdigit()

Out[7]: False

In [8]: s = "ABCD123"
s.isdigit()

Out[8]: False

In [9]: s = "123"
s.isdigit()
Out[9]: True

isalnum()
-> Checks whether the string contains alphanumeric characters or not

In [10]: s = "ABCD"
s.isalnum()

Out[10]: True

In [11]: s = "123"
s.isalnum()

Out[11]: True

In [12]: s = "ABCDE123"
s.isalnum()

Out[12]: True

islower()
--> Checks whether all the letters of the string are in lowercase or not.

In [13]: s = "abcd"
s.islower()

Out[13]: True

In [14]: s = "ABcded"
s.islower()

Out[14]: False

In [15]: s = "ABCDE"
s.islower()

Out[15]: False

isupper()
--> Checks whether all the letters of the string are in uppercase or not

In [16]: s = "ABCDE"
s.isupper()

Out[16]: True

In [17]: s = "abcd23"
s.isupper()

Out[17]: False
lower()
--> Converts all the letters of the string into lowercase

In [18]: s = "ABCDE"
s.lower()

Out[18]: 'abcde'

In [19]: s = "ABCEefg123"
s.lower()

Out[19]: 'abceefg123'

upper()
-> Converts all the letters of the string into uppercase

In [20]: s = "abcdef"
s.upper()

Out[20]: 'ABCDEF'

In [26]: s = "ABCDEeffjd123"
s.upper()

Out[26]: 'ABCDEEFFJD123'

capitalize()
--> Converts only the first letter of the string into uppercase and rest all into lowercase

In [22]: s = "ABCDeknsdkfnkf"
s.capitalize()

Out[22]: 'Abcdeknsdkfnkf'

In [23]: s = "abcDEF"
s.capitalize()

Out[23]: 'Abcdef'

In [24]: s = "i love programming"


s.capitalize()

Out[24]: 'I love programming'

title()
--> Converts the first letter of each word of the string into uppercase and rest into lower
case.
In [28]: s = "i love programming"
s.title()

Out[28]: 'I Love Programming'

In [29]: s = "abcDEF"
s.title()

Out[29]: 'Abcdef'

swapcase()
-> Converts all the letters of a string from the uppercase to the lowercase and vice-versa

In [30]: s = "I love PROGRAMMING"


s.swapcase()

Out[30]: 'i LOVE programming'

replace(old, new)
--> Replaces a substring by another substring at all places of its occurrences in the string

In [31]: s = "aaaaaabbbbCCCddd"
s.replace('a', '*')

Out[31]: '******bbbbCCCddd'

In [32]: s = " I love programming"


s.replace('m', 'M')

Out[32]: ' I love prograMMing'

In [33]: s = "ABCDEF"
s.replace('AB', 'aaaaaa')

Out[33]: 'aaaaaaCDEF'

In [37]: s = "ABCDEF"
s.replace('ab', 'aaaaaa')

Out[37]: 'ABCDEF'

find()
--> Finds the occurrence (index) of a substring in a string

In [38]: s = "aaaaaaBBBBBcccc"
s.find('a')

Out[38]: 0
In [39]: s.find('B')

Out[39]: 6

In [40]: s.find('D')

Out[40]: -1

In [41]: s.find('aB')

Out[41]: 5

In [42]: s.find('Ba')

Out[42]: -1

In [43]: s = "aaaaaaBBBBBcccc"
s.find('a', 5) # start = 5

Out[43]: 5

In [44]: s.find('a', 6) # start = 6

Out[44]: -1

In [45]: s.find('a', 2, 5) # start = 2, end = 5

Out[45]: 2

In [46]: s = "aaaaaaBBBBBcccc"
s.find('B', 2, 6)

Out[46]: -1

rfind()
In [47]: s = "aaaaaaBBBBBcccDDD"
s.rfind('a')

Out[47]: 5

In [48]: s.find('a')

Out[48]: 0

count()
--> Returns the number of occurrences of a substring in the given range of the indices

In [49]: s = "aaaaaaBBBBBcccDDD"
s.count('a')

Out[49]: 6
In [50]: s.count('B')

Out[50]: 5

In [51]: s.count('E')

Out[51]: 0

In [52]: s.count('aB')

Out[52]: 1

In [53]: s = "aaaaaaBBBBBcccDDD"
s.count('a', 3)

Out[53]: 3

In [54]: s.count('a', 5)

Out[54]: 1

In [55]: s.count('a', 6)

Out[55]: 0

In [56]: s.count('a', 2, 5)

Out[56]: 3

index()
-> Determines whether the substring occurs or not in the range of the given indices of
the string

In [57]: s = "ABCDE"
s.index('A')

Out[57]: 0

In [58]: s.index('B')

Out[58]: 1

In [59]: s.index('F')

---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
Cell In[59], line 1
----> 1 s.index('F')

ValueError: substring not found

In [60]: s.index('AB')

Out[60]: 0
In [61]: s.index('BC')

Out[61]: 1

isspace()
--> Checks whether the string contains only whitespace or not

In [62]: s = " "


s.isspace()

Out[62]: True

In [63]: s = " I "


s.isspace()

Out[63]: False

split()
--> Converts the given string into a list using specified separator

In [64]: s = "I love Programming"


s.split() # by space is separated

Out[64]: ['I', 'love', 'Programming']

In [65]: s.split('l')

Out[65]: ['I ', 'ove Programming']

In [67]: s.split('o')

Out[67]: ['I l', 've Pr', 'gramming']

In [68]: s.split('m')

Out[68]: ['I love Progra', '', 'ing']

In [66]: s.split('z')

Out[66]: ['I love Programming']

In [70]: s = "I love Programming VERY MUCH"


s.split(' ', 2) # by space is separated

Out[70]: ['I', 'love', 'Programming VERY MUCH']

In [71]: s = "I@love@Programming@VERY@MUCH"
s.split('@', 3) # by space is separated

Out[71]: ['I', 'love', 'Programming', 'VERY@MUCH']


In [72]: s.split('@', 2)

Out[72]: ['I', 'love', 'Programming@VERY@MUCH']

In [73]: s.split('@', 1)

Out[73]: ['I', 'love@Programming@VERY@MUCH']

In [74]: s.split('@')

Out[74]: ['I', 'love', 'Programming', 'VERY', 'MUCH']

partition()
--> Searches for the first occurrence of the specified substring and splits the string to
tuple. --> it will always give three elements

In [76]: s = "I love Programming VERY MUCH"


s.partition(' ')

Out[76]: ('I', ' ', 'love Programming VERY MUCH')

In [79]: s.partition('P')

Out[79]: ('I love ', 'P', 'rogramming VERY MUCH')

In [80]: s.partition('z')

Out[80]: ('I love Programming VERY MUCH', '', '')

strip()
--> Return the copy of a string after removing the leading and trailing character

In [81]: s = " I LOVE "


s.strip()

Out[81]: 'I LOVE'

In [82]: s.lstrip()

Out[82]: 'I LOVE '

In [83]: s.rstrip()

Out[83]: ' I LOVE'

startswith()
--> Check whether the string starts with a substring or not.,
In [84]: s = "i LOVE pORGRAMMING"
s.startswith('i')

Out[84]: True

In [85]: s.startswith('l')

Out[85]: False

In [86]: s.startswith('progrmming')

Out[86]: False

In [87]: s.endswith('g')

Out[87]: False

In [88]: s.endswith('G')

Out[88]: True

In [89]: s.endswith('pORGRAMMING')

Out[89]: True

join()
--> Return a new string by concatenating all of the elements in an iterable such as string,
list etc.

In [91]: s = ['I', 'love', 'Programming']


print(' '.join(s))

I love Programming

In [92]: print('#'.join(s))

I#love#Programming

In [93]: print(''.join(s))

IloveProgramming

In [94]: s = "I love Programming"


"#".join(s)

Out[94]: 'I# #l#o#v#e# #P#r#o#g#r#a#m#m#i#n#g'

In [95]: "AND".join(s)

Out[95]: 'IAND ANDlANDoANDvANDeAND ANDPANDrANDoANDgANDrANDaANDmANDmANDiANDnANDg'

In [96]: s = ['I', 'love', 'Programming']


print('AND'.join(s))

IANDloveANDProgramming
QUESTIONS
In [97]: s = "PYTHON World"

# s[1] # s[:-5] # s[-1:] # s[5] # s[::-1] # s[::-3] # s[50]

In [103… s[::-3]

Out[103]: 'doNT'

In [102… s[::-1]

Out[102]: 'dlroW NOHTYP'

In [98]: s[1]

Out[98]: 'Y'

In [99]: s[:-5]

Out[99]: 'PYTHON '

In [100… s[-1:]

Out[100]: 'd'

In [101… s[5]

Out[101]: 'N'

In [104… s[50]

---------------------------------------------------------------------------
IndexError Traceback (most recent call last)
Cell In[104], line 1
----> 1 s[50]

IndexError: string index out of range

Name the function which returns the ASCII code


of a character
'A' --> 65 'a' --> 97

In [105… ord('a') ## character input then ouput is given ascii value

Out[105]: 97

In [106… chr(97) ## ascii value and output is character

Out[106]: 'a'
In [107… wd = "CBSE 2024"
for a in range(2):
print(wd, end = ' ')

CBSE 2024 CBSE 2024

In [108… for a in range(2,5):


print(wd, end = ' ')

CBSE 2024 CBSE 2024 CBSE 2024

In [109… for a in range(0):


print(wd, end = ' ')

## NO OUTPUT

In [110… wd1 = "science"


wd2 = "computer"
wd3 = "Cyber World"
wd4 = "cyber world"

print(wd1.upper())
print(wd1.replace('n','m'))
print(wd3 == wd4)
print(wd2.replace('n', 'm'), wd1)
print(wd3.find('W'))

SCIENCE
sciemce
False
computer science
6

In [111… s1 = "Run for fun"


ln = len(s1)
b = s.isalpha()
s2 = s1.upper()
s3 = s1.capitalize()

print(ln, b, s2, s3)

11 False RUN FOR FUN Run for fun

In [112… S1 = "Computer"
S2 = "Science"

print(S1 + S2) # CONCATENATION


print(S2*3) # REPLICATION
print(S1[1:4]) # SLICING
print(S1 > S2) # COMPARISON

ComputerScience
ScienceScienceScience
omp
False

In [114… s1 = "Vision"
s2 = "2024"
s3 = "vision"

print(s1, s2)
print(len(s2))
print(s1 == s3)
print(s3.upper())
print((s1 + s2).isalnum())
print(s1*2)

Vision 2024
4
False
VISION
True
VisionVision

PROGRAMMING QUESTIONS

1. WAP code to input a sentence. Find and display the following:


(i) Number of words present in the sentence
(ii) Number of letters present in the sentence

In [116… s = input("Enter a string: ")


print("No of words: ", len(s.split()))
print("No of letters: ", len(s) - (len(s.split()) -1) )

No of words: 3
No of letters: 16

2. WAP code to accept a word/a string and display the new string after removing all
the vowles present in it.
SAMPLE INPUT: COMPUTER SCIENCE
SAMPLE OUTPUT: CMPTR SCNC

In [117… s = "COMPUTER SCIENCE"


s_n = ""

for i in s:
if i.upper() in 'AEIOU':
continue
else:
s_n += i

print(s_n)

CMPTR SCNC

In [ ]:

You might also like