Document 7
Document 7
STRINGS IN PYTHON
Sequence of characters (UNICODE) enclosed in single (‘ ’) or double
(“ ”) quotes.
Triple quotes are used for strings that span multiple lines.
Example
Example:
>>>s1 = ‘’ #empty string, length is zero
>>> print(s1)
>>> s4='''Hello\
children'''
>>> print(s4)
Hellochildren
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
>>> for i in s:
print(i)
h
e
l
l
o
c
l
a
s
s
!
c
l
a
s
s
!
Q2
Output
print (rev)
>>> ‘hello’ * 5
Hellohellohellohellohello
>>> 70 * ‘-‘
---
COMPARISON OPERATORS
Relational Operators <, >, <=, >=, ==, != can be used to compare strings
Example
Unicode values and ASCII values are used to compare strings.(like dictionary order)
ord() takes a single character and returns the corresponding ordinal Unicode.
Syntax:
ord(<single character>)
>>>ord(‘a’)
97
>>>ord(‘ ’)
53
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
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'
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
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
R=R+y
print (R)
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
output