0% found this document useful (0 votes)
21 views27 pages

Document 7

The document discusses various methods and functions related to strings in Python. It describes how to define, access, manipulate and compare strings. Some key string methods covered include len(), upper(), lower(), count(), find(), split(), replace(), join() etc. Examples are provided for each method to demonstrate their usage.

Uploaded by

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

Document 7

The document discusses various methods and functions related to strings in Python. It describes how to define, access, manipulate and compare strings. Some key string methods covered include len(), upper(), lower(), count(), find(), split(), replace(), join() etc. Examples are provided for each method to demonstrate their usage.

Uploaded by

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

7.

STRINGS IN PYTHON
Sequence of characters (UNICODE) enclosed in single (‘ ’) or double
(“ ”) quotes.

Strings, integers, floats are immutable.

Triple quotes are used for strings that span multiple lines.

Example

Example:
>>>s1 = ‘’ #empty string, length is zero
>>> print(s1)

>>> s2='Computer Science'


>>> print(s2)
Computer Science

>>> s2='Computer\tScience' #\t – tab will work


>>>print(s2)
Computer Science
>>>S3 = “Python Program”
>>>print(s3)
Python Program

>>> s4='''Hello\
children'''

>>> print(s4)
Hellochildren

>>> s4 = ''' Hello


children'''
>>> print(s4)
Hello
children
*len() function / method
To find the length of the string.

Example
>>>n = ‘abc’
>>>len(n)
3
>>>n=’a123’
>>>len(n)
4
>>>n=’@ #$’
>>>len(n)

>>> s6='''a
bc
def'''
>>> len(s6)
8
>>> s6='''a\
bc\
def'''
>>> len(s6)
6
TRAVERSING A STRING

Each character is stored in continuous location in the memory. Accessing all the elements
of the string one after the other by using the subscript or index value typed in [].

** Elements can be accessed using positive index (forward) and negative index (backward)

Example
S = ‘hello class!’

String
h E l l o C l a s s !
S
+ ve 0 1 2 3 4 5 6 7 8 9 10 11
- ve -12 -11 -10 -9 -8 -7 -6 -5 -4 -3 -2 -1

>>> s='hello class!'


>>> s[0] or print(s[0])
'h'
>>> s[5]
''
>>> s[8]
'a'
>>> s[11]
'!'
>>> s[-1]
'!'
>>> s[7]
'l'
>>> s[-12]
'h'
 Iterating through string using for loop
>>> for i in 'abcd':
print(i)
a
b
c
d

>>> for i in s:
print(i)
h
e
l
l
o

c
l
a
s
s
!

 Iterating through string using while loop


Output
h
e
l
l
o

c
l
a
s
s
!

 len() – returns the number of items in an object.


 is a built-in function that is returns the length of the
string(number of characters) , list, tuple or dictionary.
Q1
Output

Enter a string Learning is fun


Enter a character to be searched i
i occurs 2 times

Q2

Output

Enter a string reverse string


gnirts esrever
SPECIAL STRING OPERATORS
Strings can be manipulated using
1. Concatenation (+) operators

>>> ‘My’ + ‘Class’


My Class

>>> ‘Good ‘ + ‘ morning ’ + ‘ students ’

Good morning strudents


>>>a,b,c =’abc’,’edf’,’qwe’
>>>a+b+c
abcedfqwe

To reverse a string using a second variable


#reverse a string
s =input("Enter a string ")
rev =''
for i in range(len(s)-1,-1,-1):
rev = rev + s[i]

print (rev)

2. Replication (*) operators

>>> ‘hello’ * 5
Hellohellohellohellohello

>>> 70 * ‘-‘
---

3. Membership operators (in , not in)

>>> ‘a’ in ‘day’


True
>>> ‘el’ in ‘hello’
True
>>>’eo’ in ‘hello’
False

COMPARISON OPERATORS

Relational Operators <, >, <=, >=, ==, != can be used to compare strings

Example

>>> "a" == "a"


True
>>> "abc" == "abc"
True
>>> "ab" != "abc"
True
>>> "A" != "a"
True
>>> "abc" > "ABC"
True
>>> "abC" > "aBC"
True

Unicode values and ASCII values are used to compare strings.(like dictionary order)

Characters Ordinal Values


‘0’ to ‘9’ 48 to 57
‘A’ to ‘Z’ 65 to 90
‘a’ to ‘z’ 97 to 122

ord() and chr() function

ord() takes a single character and returns the corresponding ordinal Unicode.

Syntax:
ord(<single character>)
>>>ord(‘a’)
97
>>>ord(‘ ’)
53

chr() takes an integer and returns the character corresponding it.

Syntax:
chr(<int>)

Example

>>> ord('A')
65
>>> ord('a')
97
>>> ord('Z')
90
>>> ord('z')
122
>>> ord('*')
42

>>> chr(65)
'A'
>>> chr(90)
'Z'
>>> chr(97)
'a'
>>> chr(110)
'n'
>>> chr(122)
'z'

SLICING

Slicing continuous characters from a string.

String C O M P U T E R
F Index 0 1 2 3 4 5 6 7
B Index -8 -7 -6 -5 -4 -3 -2 -1
Examples
>>> s='COMPUTER' #’computer’[0:5]
>>> s[0:5]
'COMPU'
>>> s[2:6]
'MPUT'
>>> s[-6:-2:1]
'MPUT'
>>> s[-2:-6] “string”[start:end:step]
''
>>> s[-2:-7:-1]
'ETUPM'
>>> s[-2:-7:-2]
'EUM'
>>> s[2:]
'MPUTER'
>>> s[-4:]
'UTER'
>>> s[:6]
'COMPUT'
>>> s[:]
'COMPUTER'
>>> s[::2]
'CMUE'
>>> s[::-1]
'RETUPMOC'
>>> s #no change to string
'COMPUTER'
>>> s[::-2] computer
'RTPO'

NOTE:
>>> s='computer science'
>>> s[0:5:-1]
''
>>> s[:5:-1]
'ecneics re'
>>> s[:4:-2]
'enisrt'
>>> s[4::-1]
'upmoc'

STRING FUNCTIONS AND METHODS for string


manipulation
Built-in functions and methods for string manipulations.

4. len()
Returns the length of the string.
>>>len(‘we’)
2
5. capitalize()
Returns the copy of the string with its first character capitalized.
>>> s='computer science'
>>> s.capitalize() #string.capitalize()
'Computer science'

6. isalnum()
Returns True if the characters in the string are alphanumeric and
there is at least one character, False otherwise.
>>> 'abc123'.isalnum()
True
>>> 'Computer'.isalnum()
True
>>> '1234'.isalnum()
True
>>> ‘ ’.isalnum()
False
>>>s= ‘Computer Science’ #contains space
>>>s.isalnum()
False

7. isalpha()
Returns True if all the characters in the string are alphabetic and
there is at least one character, False otherwise.
>>> 'abcd'.isalpha()
True
>>> 'abc123'.isalpha()
False
>>> '123'.isalpha()
False
>>> ''.isalpha()
False
>>> 'abc wer'.isalpha()
False

8. isdigit()
Returns True if all the characters in the string are digits and there is
at least one character, False otherwise.
>>> 'abcd'.isdigit()
False
>>> '123'.isdigit()
True
>>> ''.isdigit()
False
>>> 'abc123'.isdigit()
False

9. islower()
Returns True if all cased characters in the string are lowercase. and
there is at least one character, False otherwise.

>>> 'hello'.islower()
True
>>> 'ABCD'.islower()
False
>>> 'asd123'.islower()
True
>>> '123q'.islower()
True

10. isupper()
Returns True if all cased characters in the string are uppercase. and
there is at least one character, False otherwise.

>>> 'hello'.isupper()
False
>>> 'ABCD'.isupper()
True
>>> ‘ASD123'.isupper()
True
>>> '123q'.isupper()
False

11. isspace()
Returns True if there are only whitespace characters in the string.
There must be at least one character, False otherwise.
>>> x=' '
>>> x.isspace()
True
>>> x=''
>>> x.isspace()
False
>>> x='ab cd'
>>> x.isspace()
False

12. lower()
Returns a copy of the string converted to lowercase.
>>> b='ABC DEF'
>>> print(b.lower())
abc def
>>>b
‘ABC DEF’

>>>str.lower(b)
‘abc def’

13. upper()
Returns a copy of the string converted to uppercase.
>>> a ='abcd'
>>> b=a.upper()
>>> print(b)
ABCD

14. lstrip()
Returns a copy of the string with leading characters removed. (all
comibinations)
If used without any arguments, it removes the leading whitespaces.
>>> s=' abc'
>>> s.lstrip()
'abc'
>>> x='They are'
>>> x.lstrip('the')
'They are'
>>> x.lstrip('The')
'y are'
>>> x.lstrip('he')
'They are'
>>> x.lstrip('T')
'hey are'
>>> x.lstrip('heT')
'y are'
15. rstrip()
returns a copy of the string with trailing characters removed.
If used without arguments, it removes the leading white apaces.
>>> s='qwert '
>>> s.rstrip()
'qwert'
>>> x='qwert'
>>> x.rstrip('ert')
'qw'
>>> x.rstrip('ter')
'qw'

16. split()
Splits the string and creates a list.
>>> x='There is a tree'
>>> y = x.split()
>>> y
['There', 'is', 'a', 'tree']
>>> y = x.split('e')
>>> y
['Th', 'r', ' is a tr', '', '']

17. title()
returns the string with first letter of every word in the string in
uppercase and rest in lowercase.
>>> string = 'hELLo how arE you'
>>> string.title()
'Hello How Are You'

18. replace()
replaces all the occurrences of the old string with new string.
>>> string = 'hello how are you'
>>> string.replace('hello','hi')
'hi how are you'

19. find()
searches for the first occurrence of the sub string in a string.
Returns the lowest index in the string where the substring sub is
found within the slice range of start and end.
Return -1 if sub is not found.
>>> t='there is a there is no'
>>> t.find('is')
6
>>> t.find('er',4,18)
13
>>> t.find('er',4,10) #NOTE
-1

20. index()
Searches the first occurrence of the substring in a string and returns
the starting index of the substring in a string. If the substring is
found it raises an exception.
>>> string = 'hello how are you'
>>> string.index('are')
10
>>> string.index('is')
Traceback (most recent call last):
File "<pyshell#11>", line 1, in <module>
string.index('is')
ValueError: substring not found

21. count()
returns the number of times substring occurs in the given string.
We can specify the starting & ending index.
>>> string = 'day is how is is find is is is low'
>>> string.count('is')
6
>>> string.count('is',20,len(string))
3
>>> string.count('abc')
0

22. swapcase()
converts and return all uppercase characters into lowercase & vice
versa.
>>> string='AbCdEFg'
>>> string.swapcase()
'aBcDefG'
23. join()
returns the string in which the string elements are joined by as string
separator.
>>> string='AbCdEFg'
>>> '@'.join(string)
'A@b@C@d@E@F@g'
>>> x = '---'
>>> x.join(string)
'A---b---C---d---E---F---g'
24. partition()
25. startswith()
returns True if the given string starts with the specified substring,
else False.
>>> s ='abcdefg'
>>> s.startswith('ab')
True
>>> s.startswith('ba')
False
26. endswith()
returns True if the given string ends with the specified substring, else
False.
>>> string='AbCdEFg'
>>> string.endswith('Fg')
True
>>> string.endswith('gF')
False

Write Python programs for the following:

27. Count the number of letters in the string entered by the user. (without
using built-in functions)

Output
28. Count number of uppercase, lowercase letters and digits separately.

OUTPUT

29. Count the number of spaces.

30. Count the number of vowels.

31. Count the number of words. (Use split())

32. Count the number of ‘is’ present in the string.


33. To count the words having more than 5 characters in it.

34. Reverse a string.


X = input(“Enter a string”)
for y in X:

R=R+y
print (R)

35. Check if a string is palindrome or not.


Example : MADAM

st = input("Enter a string : ")


if st == st[::-1]:
print(st," is a pallindromic string ")
else:
print(st," is not a pallindrome ")

output
2nd logic
st = input("Enter a string : ")
l = len(st)
l=l-1

for i in range(0,len(st)//2+1):
if st[i] != st[l]:
print(st," is not pallindromic")
break
l=l-1

else:
print(st, " is pallindrome")

3rd logic
st = input("Enter a string : ")
l = len(st)
l=l-1
flag = 0
for i in range(0,len(st)//2+1):
if st[i] != st[l]:
flag = 1
break
l=l-1
if flag == 0:
print(st," is a pallindrome")
else:
print(st, " is not a pallindrome")

36. To read a string and display the longest substring in the entered string.
st = input("Enter a string : ")
x = st.split()
l=0
long =''
for i in x: #EXAMPLE : [‘THIS’,’IS’,’A’,’LIST’]
if len(i) > l:
l = len(i)
long = i

print("Longest word ",long)

output

37. Remove vowels from a string.


X = input(“Enter a string”)
R= ‘’
print(“orginal string “,X)
for y in X:
if y is not ‘AEIOUaeiou’:
R=R+y
print (‘String after removing vowes ‘,R )

You might also like