[go: up one dir, main page]

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

05 Python Strings

string functions in python
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)
3 views8 pages

05 Python Strings

string functions in python
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/ 8

PYTHON STRINGS

A sequence in python is a linearly ordered set of elements accessed by an index number.


Lists ,tuples, and strings are all sequences
A string is a sequence of Unicode characters enclosed with in single quotes or double
quotes or triple single quotes or triple double quotes
Example:
S =’python’
S = “python”
S = ‘’’python’’’
S = “””python”””
Example:
S=” Tom’s birth day ”
S=’ Tom said, “I am busy today” ’
S=’ Tom said,” I\’m busy today” ‘
S=’’’Hey there !
Welcome to Python tutorial’’’
Concatenation:
S1=”Good”
S2=”Morning”
S3= S1+” “+S2
Print(S3)
Format of string:
S1=”Hey”
S2=”there”
S3=”all”
S4=”{} {} , {}!”.format(S1,S2,S3)
Python’s string is an immutable object modifications are not allowed once it is created.
Indexing, slicing are valid operations on any sequence.
Strings allow both positive indexing and negative indexing . (flexibility to access from both
left to right or right to left)
For any sequence s, len(s) gives its length , and s[k] retrieves element at index k.

Slice operation:
The slice operation s [ start : stop : step ] returns a subsequence of a sequence starting
from start index location up to but not including the stop index.
S [ start : stop : step ]
step value can be either +ve or –ve
if step value is +ve then it should be forward direction (left to right) and to consider index
from start to stop - 1
if step value is -ve then it should be backward direction(right to left) and to consider index
from start to stop + 1
In the backward direction if the stop value is -1 then result is always empty string .
In the forward direction if the stop value is 0 then result is always empty string

Left to Right forward direction:


default value for start: 0
default value for stop : length of the string
default value for step: +1

In backward direction:
default value for start: -1
default value for stop : - (length of the string +1)
Either forward or backward direction, we can take both +ve and -ve values for start and stop
Example:
s = ’ python ’
Right to Left (L <- R )
-6 -5 -4 -3 -2 -1 -ve index -1 to – ( length )

p y t h o n

0 1 2 3 4 5 +ve index 0 to ( length-1 )


Left to Right (L -> R)

The Slice Operation


s=’python’
print ( s [ 2 : 5 : 1 ] ) #tho (third character to fifth character)
print( s [ 3 : ] ) => s[3:6:1] #hon => s[3:6:1]
print(s [ : 4 ] ) #pyth (returns first four characters)
print(s [ : ] ) #python
print( s [ - 6 : - 4 ] ) #py
print( s [ -3 : ] ) #hon
print(s [ : - 5 ] ) #p
print( s [ : : ] ) #python
print( s [ : : -1] ) #nohtyp
print(s [8 : 1 : -2 ] ) # nh
Python string slicing handles out of range indexes gracefully.
>>> s = 'python'
>>> s[100:]
''
>>>s[2:50]
'thon'
Operations on strings
Example:
s=’ hello ’ w=’ ! ’
len(s) #5
s[0] #h
s[1:4] #’ell’
s[1:] #’ello’
s.count(‘e’) #1
s.count(‘x’) #0
s.index(‘e’) #1
s.index(‘x’) #ValueError : substring not found
s.index(4) #TypeError must be str, not int
‘h’ in s #True
S+w #hello!
min(s) #’e’
max(s) # ‘o’
sum(s) #error
String functions
strip() , enumerate() , split() , join ()
The enumerate() function returns an enumerate object. It contains the index and value of
all the items in the string as pairs. This can be useful for iteration.
split () function to splits the string according to a splitting character, the default splitting
character is space.
join() function joins a group of strings

#program to illustrate string functions


s1=" python "
print ( s1 )
print ( len (s1) )
print ( s1.strip() )
print (len (s1.strip() ) )
s2=" Introduction to Python 3.7 "
print (s2.split() ) #default splitting character is space
print (s2.split(“.” ) )
t = ( ‘ Alan ’ , ’ Kate ’ , ’ Bob ’ )
s3=’:’.join(t)
print(s3)
s4 = ‘ successful '
# enumerate()
print ( tuple (enumerate ( s4 ) ) )
print ( list ( enumerate ( s4 ) ) )
print ( " successful “ . count ( 's’ ) )

Python String Methods

Method Description
lower() Converts a string into lower case
upper() Converts a string into upper case
find() returns the index value of the string where
substring is found between begin index and end
index
index() Searches the string for a specified substring and
returns the position of where it was found. It
throws an exception if the sub string is not found.
title() Converts the first character of each word to upper
case
swapcase() Swaps cases, lower case becomes upper case and
vice versa
split() Splits the string at the specified separator, and
returns a list
isalpha() Returns True if all characters in the string are in
the alphabet
isupper() Returns True if all characters in the string are
lower case
islower() Returns True if all characters in the string are
lower case
isdigit() Returns True if all characters in the string are
digits
replace() Returns a string where a specified value is
replaced with a specified value
join() Joins the elements of an iterable; the string
representation of the given sequence.
startswith() Returns true if the string starts with the specified
value
endswith() Returns true if the string ends with the specified
value

#program to take string as input and print the positive and negative index of each of the
character
s=input('Enter a string')
i=0
k=len(s)
for ch in s:
print('s[{}]=s[{}]={}'.format( i ,i-k , ch ) ))
i=i+1

p y t h o n => k=len(s) = 6
0 1 2 3 4 5
-6 -5 -4 -3 -2 -1
+ve -ve
0 -6 => 0-6=-6 positive index = i => negative index =i-len(s)
1 -5 => 1-6=-5
2 -4 => 2-6=-4
3 -3 => 3-6=-3
4 -2 => 4-6=-2
5 -1 => 5-6=-1
Test Cases:

Enter a string; python


s[0]=s[-6]=p
s[1]=s[-5]=y
s[2]=s[-4]=t
s[3]=s[-3]=h
s[4]=s[-2]=o
s[5]=s[-1]=n

#program to check given string is a pallindrome


s=input('Enter a string:')
if s==s[::-1]:
print('Pallindrome')
else:
print('Not a pallindrome')

Test Cases

Test Case -1 :Enter a string:madam


Pallindrome
Test Case-2:Enter a string:welcome
Not a pallindrome

#program to print number of lower case and upper case characters and number of digits in
a sentence
s=input('Enter the line of text :')
uc,lc,dc=0,0,0
for ch in s:
if ch.isupper():
uc=uc+1
elif ch.islower():
lc=lc+1
elif ch.isdigit():
dc=dc+1
else:
pass
print('Uppercase Characters:',uc)
print('Lowercase Character:',lc)
print('Number of digits:',dc)

Test Cases

Enter the line of text :Industry 4.0 Automation


Uppercase Characters: 2
Lowercase Character: 16
Number of digits: 2

You might also like