0% found this document useful (0 votes)
13 views24 pages

Strings and Characters

Uploaded by

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

Strings and Characters

Uploaded by

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

STRINGS AND

CHARACTERS
Creating strings

String is a sequence data type.


String is a group of characters. Strings are useful because most of the data
we use in daily life will be in the form of strings.
For example name, address etc.
Strings are created in python by enclosing a group of characters in single
or double or triple single or triple double quotes
Ex:
S1=“hello ‘how’ are you”
S2=‘hi how \tare you’
S3= ‘’’ hello \\n“hi” ‘’’
S4=“”” “hello”, ‘hi’ “””
S=str(“hello”)
Python program to read a string and print each characters in string and
find length of string without using built in function

Python program to read a string and print each characters in string


in single line both in forward and backward direction using positive and
negative indices
Slicing the string
Slice represents a part or piece of a string. The format of slicing is
stringname[start: stop :stepsize]
if start and stop is not specified then slicing is done from 0th to n-1th
elements. stepsize is not written then it is taken to be 1.
str=‘Core python’
S=str[2:9:2]
print(S)
Output
r yh
Write the output of the
following:
s='core python'
print(s[0:9:1]) #core pyth
print(s[0:9:2]) #cr yh
print(s[::]) # core python
print(s[::2]) #cr yhn
print(s[2::]) #re python
print(s[:2:]) #co
print(s[::-1]) #nohtyp eroc
print(s[-4::]) #thon
print(s[-4::-1]) #typ eroc
print(s[-1:-4:-1]) #noh
Strings are Immutable
An immutable object is an object whose content cannot be changed. mutable is the one whose
content can be changed. Strings and tuple are immutable where as list and dictionary are mutable

Ex1:
s='BEC BGK'
print(s)
print(s[1])
s[1]=‘k’

TypeError: 'str' object does not support item assignment


Ex2: Persormance and Security
S=“Tarun”
print(S,id(S))
S=“V”+S[1::]
Print(S,id(S)
Repeating and Concatenation of string
* Operator repeats the number of elements in string object by n times
Example
s=‘core python’
print(s*2)
Print(s[5:11]*2)
Output
core pythoncore python
pythonpython
+ operator concatenates the strings
s=‘core’;s1=‘python’
print(s+s1)
Output
corepython
Checking membership

in and not in operator are used to check given substring is present in


main string or not.
in operator returns True if present and not in operator returns False if
present irrespective of cases

Example: Write a python program to check given substring is present


in main string or not
comparison of strings
Relational operators <,<=,>,>=,== and != can be used to compare two
string objects These operators returns Boolean value True or False

Example: Write a python program to read two strings and check are
they equal or first string is greater than second or smaller. Print
appropriate messages
Removing space from string
A space is also considered as a character inside a string. Sometime
unnecessary spaces in a string lead to wrong result.
if ‘bec ’==‘bec’:
print(“equal”)
else:
print(“not equal”)
Removing space from string
Python provides following functions

function Description Example


rstrip() Removes spaces which are n=“ bec cse "
present at the right side of the print(n.rstrip())
strings print(n.lstrip())
print(n.strip())
lstrip() Removes spaces which are
present at the left side of the Output
strings bec cse
bec cse
bec cse
strip() Removes spaces which are
present at both side of the
strings
Finding substrings

find(),rfind and index(),rindex()


The above methods are used to search for the sub string in main string
and returns last occurrences of substring in a main string.
Syntax for these methods
Mainstring.find(substring,beginning,ending)
find()-returns -1 if substring is not found in the main string
Mainstring.index(substring,beginning,ending)
Index()- returns ‘ValueError’ if substring is not found in the main string.
find() and index() returns only first occurance of the substring when
substring occurs several times
rfind() and rindex()-Used to search strings from right to left
Python program to find the given substring position in main string using find(),rfind(),index() and rindex() method

ms=input("Enter main string:")


ss=input("Enter the sub string:")

p=ms.find(ss,0,len(ms))
if p==-1:
print("Not prsent")
else:
print('prsent at ',p)
p=ms.index(ss,0,len(ms))
if p=='ValueError':
print("Not prsent")
else:
print('prsent at ',p)
p=ms.rfind(ss,0,len(ms))
if p==-1:
print("Not prsent")
else:
print('prsent at ',p)

p=ms.rindex(ss,0,len(ms))
if p=='ValueError':
print("Not prsent")
else:
print('prsent at ',p)
Python program to display all positions of a sub string in a given main string
ms=input("Enter main string:")
ss=input("Enter the sub string:")
i=0
f=False
l=len(ms)
while i<l:
p=ms.find(ss,i,l)
if p!=-1:
print(ss,' is found at',p+1)
i=p+1
f=True
else:
i=i+1
if f==False:
print('Substring not found:')
Counting substring in a string
count() is available to count the number of occurrences of a sub string in a
main string
stringname.count(substring)
Returns an integer number that represents how many times the substring
is found in main string if not found then returns zero
stringname.count(substring,beg,end)
Returns an integer number that represents how many times the substring
is found in main string from beginning to end position
If substring is not found in main string then returns zero
Counting substring in a string
s='BEC BGK CSE BEC'
print(s.count('EC'))
print(s.count('E'))
print(s.count('B',3,len(s)))
print(s.count('S',11,len(s)))
print(s.count('ISE'))

Find all occurrences of “USA” in a given string ignoring the case


Given:
str1 = "Welcome to USA. usa awesome, isn't it?"
replace(),startswith() and
endswith() function of string
class
replace() function of string class replaces the substring in string with
another substring
Syntax
Stringname.replace(old,new)
Example:
S=“BEC BGK EC BGK”
print(S.replace(‘EC’,’CSE’)
Output
BCSE BGK CSE BGK
startswith() and endswith()
These methods are used to check string starts with a particular
substring or not.
If starts with substring then this function returns True otherwise False.
Example:
S=“This is Python”
print(S.startswith(‘This’))
Print(S.endswith(“end”))
Output
True
False
split() and join()

Split() splits a string into pieces. These pieces are returned as a list.
Example:split a string wherever , occurs in a given string
Syntax:
stringname.split(splitting character)
S=“one,two,three,four”
S1=S.split(‘,’)
Print(s1)
output
['one', 'two', 'three', 'four’]
Example: python program to read a string of numbers separated by
space. Split the string at space. Print the numbers and find their sum
join()
Join() does the reverse of split(). Joins the string elements of list or tuple using
a separator
separator.join(list/tuple)
separator represents the character to be used to join the elements of string in a
list or tuple
l=['A','B','C']
k=''.join(l)
print(k)
Output
ABC

Example: Read a list of numbers in a word and join these words using
underscore and print final string
Changing case of a string:
swapcase(),title(),upper(),lower()
s=‘Python is the future’
print(s.upper())
PYTHON IS THE FUTURE
print(s.lower())
python is the future
print(s.swapcase())
PYTHON IS THE FUTURE
Print(s.title())
Python Is The Future
String Testing methods
isalnum() –returns True if all characters in string are alphanumeric(a-
z,A-Z,0-9) otherwise False
S=“delhi98”
print(S.isalnum())
isalpha()-returns True if string has all characters alphabetic(A-Z,a-z)
S=‘d111’
print(s.isalpha())
Isdigit()-returns True if string contains only numeric digits(0-9)
otherwise False
s=‘111’
print(s.isdigit())
Contd..

islower():returns True if string contains lower case letters otherwise


False
s="deee hi"
print(s.islower())
isupper():returns True if string contains uppercase letters otherwise
False
s="deee hi"
print(s.isupper())
Istitle():returns True if each word of a string starts with a capital letter
otherwise False
s="Python Core"
print(s.istitle())
Contd..
isspace()-returns True if the string contains only spaces otherwise
False
S=‘ ‘
print(S.isspace())

Example: Python program to know the type of character entered by


the user.
Python program to insert a sub string in a string in a particular position

Python program to read a string consists of names separated by space.


Search for name entered by user in string. If present print the position.

You might also like