[go: up one dir, main page]

0% found this document useful (0 votes)
10 views57 pages

Strings

Uploaded by

thanujasoma2004
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)
10 views57 pages

Strings

Uploaded by

thanujasoma2004
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/ 57

Dr. Rameswara Reddy.K.

PYTHON STRINGS Associate Professor


Dept.of CSE
GPREC
WHAT IS STRING?
The most commonly used object in any project and in any programming language
is String only.
Any sequence of characters within either single quotes or double quotes is
considered as a String.
Syntax:
s=‘Ram'
s=“Shriyaan"
Eg: ch='a'
type(ch)
HOW TO DEFINE MULTI-LINE
STRING LITERALS
We can define multi-line String literals by using triple single or double quotes.
We can also use triple quotes to use single quotes or double quotes as symbol inside String
literal.
Eg:
s='This is ' single quote symbol' ==>invalid
s='This is \' single quote symbol' ==>valid
s="This is ' single quote symbol"====>valid
s='This is " double quotes symbol' ==>valid
s=‘hello “GPREC” ‘CSE-A’ students' ==>invalid
s=“hello “GPREC” ‘CSE-A’ students” ==>invalid
HOW TO ACCESS
CHARACTERS OF A STRING:
We can access characters of a string by using the following ways.
1. By using index
2. By using slice operator
By using index:
Python supports both +ve and -ve index.
+ve index means left to right(Forward direction)
-ve index means right to left(Backward direction)
Eg:
>>> s=‘Shriyaan'
>>> s[0]
‘S'
>>> s[4]
‘y'
>>> s[-1]
‘n'
>>> s[10]
IndexError: string index out of range
ACCESSING CHARACTERS BY
USING SLICE OPERATOR
Syntax: s[beginindex:endindex:step]
beginindex:From where we have to consider slice(substring)
endindex: We have to terminate the slice(substring) at endindex-1
step: incremented value
>>> s="Learning Python is very very easy!!!"
>>> s[1:7:1]
'earnin'
>>> s[1:7]
'earnin'
>>> s[1:7:2]
'eri'
>>> s[:7]
'Learnin'
>>> s[7:]
'g Python is very very easy!!!'
>>> s[::]
'Learning Python is very very easy!!!'
>>> s[:]
'Learning Python is very very easy!!!'
>>> s[::-1]
'!!!ysae yrev yrev si nohtyP gninraeL'
In forward direction:
default value for begin: 0
default value for end: length of string
default value for step: +1
In backward direction:
default value for begin: -1
default value for end: -(length of string+1)
MATHEMATICAL OPERATORS
FOR STRING:
We can apply the following mathematical operators for Strings.
1. + operator for concatenation
2. * operator for repetition
print(“CSE-A”+” Students”)
print(“CSE”*2)
CHECKING MEMBERSHIP:
We can check whether the character or string is the member of another string or not
by using in and not in operators
s=‘Shriyaan'
print(‘h' in s) #True
print('z' in s) #False
s=input("Enter main string:")
subs=input("Enter sub string:")
if subs in s:
print(subs,"is found in main string")
else:
print(subs,"is not found in main string")
LEN()
We can use len() function to find the number of characters present in the string
Eg:
s=‘Shriyaan'
print(len(s)) #8
WRITE A PROGRAM TO ACCESS EACH CHARACTER
OF STRING IN FORWARD AND BACKWARD
DIRECTION BY USING WHILE LOOP?
s="Learning Python is very easy !!!"
n=len(s)
i=0
print("Forward direction")
while i<n:
print(s[i],end=' ')
i +=1
print("Backward direction")
i=-1
while i>=-n:
print(s[i],end=' ')
i=i-1
s="Learning Python is very easy !!!"
print("Forward direction")
for i in s:
print(i,end=' ')
print("Forward direction")
for i in s[::]:
print(i,end=' ')
print("Backward direction")
for i in s[::-1]:
print(i,end=' ')
COMPARISON OF STRINGS
We can use comparison operators (<,<=,>,>=) and equality operators(==,!=) for strings.
Comparison will be performed based on alphabetical order.
Eg:
s1=input("Enter first string:")
s2=input("Enter Second string:")
if s1==s2:
print("Both strings are equal")
elif s1<s2:
print("First String is less than Second String")
else:
print("First String is greater than Second String")
FINDING SUBSTRINGS:
For forward direction:
find()
index()
For backward direction:
rfind()
rindex()
FIND():
s.find(substring)
Returns index of first occurrence of the given substring. If it is not available
then we will get -1
Eg:
s="Learning Python is very easy"
print(s.find("Python")) #9
print(s.find("Java")) # -1
print(s.find("r"))#3
print(s.rfind("r"))#21
Note: By default find() method can search total string. We can also specify
the boundaries to
search.
s.find(substring,bEgin,end)
It will always search from bEgin index to end-1 index
Eg:
1) s="durgaravipavanshiva"
2) print(s.find('a'))#4
3) print(s.find('a',7,15))#10
4) print(s.find('z',7,15))#-1
INDEX() METHOD:
index() method is exactly same as find() method except that if the specified substring
is not available then we will get ValueError.
Eg:
s=input("Enter main string:")
subs=input("Enter sub string:")
try:
n=s.index(subs)
except ValueError:
print("substring not found")
else:
print("substring found")
PROGRAM TO DISPLAY ALL POSITIONS
OF SUBSTRING IN A GIVEN MAIN STRING
s=input("Enter main string:")
subs=input("Enter sub string:")
flag=False
pos=-1
n=len(s)
while True:
pos=s.find(subs,pos+1,n)
if pos==-1:
break
print("Found at position",pos)
flag=True
if flag==False:
print("Not Found")
COUNTING SUBSTRING IN THE
GIVEN STRING:
We can find the number of occurrences of substring present in the given string by using
count()
method.
1. s.count(substring) ==> It will search through out the string
2. s.count(substring, bEgin, end) ===> It will search from begin index to end-1 index
Eg:
s="abcabcabcabcadda"
print(s.count('a')) #6
print(s.count('ab')) #4
print(s.count('a',3,7))#2
REPLACING A STRING WITH
ANOTHER STRING:
s.replace(oldstring,newstring)
inside s, every occurrence of oldstring will be replaced with newstring.
Eg:
s="Learning Python is very difficult"
s1=s.replace("difficult","easy")
print(s1)
Output:
Learning Python is very easy
TO CHECK TYPE OF
CHARACTERS PRESENT IN A
STRING:
Python contains the following methods for this purpose.
isalnum(): Returns True if all characters are alphanumeric( a to z , A to Z ,0 to9 )
isalpha(): Returns True if all characters are only alphabet symbols(a to z,A to Z)
isdigit(): Returns True if all characters are digits only( 0 to 9)
islower(): Returns True if all characters are lower case alphabet symbols
isupper(): Returns True if all characters are upper case alphabet symbols
isspace(): Returns True if string contains only spaces
istitle(): Returns True if string is in title case
Eg:
print(‘Ram123'.isalnum()) #True
print(‘ram786'.isalpha()) #False
print(‘ram'.isalpha()) #True
print(‘ram'.isdigit()) #False
print('786786'.isdigit()) #True
print('abc'.islower()) #True
print('Abc'.islower()) #False
print('abc123'.islower()) #True
print('ABC'.isupper()) #True
print('Learning python is Easy'.istitle()) #False
print('Learning Python Is Easy'.istitle()) #True
print(' '.isspace()) #True
CHANGING CASE OF A
STRING:
We can change case of a string by using the following 4 methods.
1. upper()===>To convert all characters to upper case
2. lower() ===>To convert all characters to lower case
3. swapcase()===>converts all lower case characters to upper case and all
upper case characters to lower case
4. title() ===>To convert all character to title case. i.e first character in every
word should be upper case and all remaining characters should be in lower
case.
5. capitalize() ==>Only first character will be converted to upper case and all
remaining characters can be converted to lower case
Eg:
s='learning Python is very Easy'
print(s.upper())
print(s.lower())
print(s.swapcase())
print(s.title())
print(s.capitalize())
Output:
LEARNING PYTHON IS VERY EASY
learning python is very easy
LEARNING pYTHON IS VERY eASY
Learning Python Is Very Easy
Learning python is very easy
SPLITTING OF STRINGS:
We can split the given string according to specified seperator by using split() method.
l=s.split(seperator)
The default seperator is space. The return type of split() method is List
Eg1:
s=“GPREC CSE Students"
l=s.split()
for x in l:
print(x)
Output:
GPREC
CSE
Students
JOINING OF STRINGS:
We can join a group of strings(list or tuple) wrt the given seperator.
s=seperator.join(group of strings)
Eg:
t=('sunny','bunny','chinny')
s='-'.join(t)
print(s)
Output: sunny-bunny-chinny
Eg:
l=['hyderabad','singapore','london','dubai']
s=':'.join(l)
print(s)
Output:
hyderabad:singapore:london:dubai
FORMATTING THE STRINGS:
We can format the strings with variable values by using replacement operator {} and
format()
method.
Eg:
name=‘Ram'
salary=100000
age=39
print("{} 's salary is {} and his age is {}".format(name,salary,age))
print("{0} 's salary is {1} and his age is {2}".format(name,salary,age))
print("{x} 's salary is {y} and his age is {z}".format(z=age,y=salary,x=name))
1. Create a string made of the first, middle and last
character
Input : Shriyaan
Output: Syn
str1 = ‘Shriyaan'
print("Original String is", str1)
res = str1[0]
l = len(str1)
mi = int(l / 2)
res = res + str1[mi]
res = res + str1[l - 1]
print("New String:", res)
Write a program to create a new string made of the middle three characters of an
input string.
i/p: Original String is Hyderabad
o/p: Middle three chars are: era
i/p : Original String is Bangalore
o/p: Middle three chars are: gal
def get_middle_three_chars(str1):
print("Original String is", str1)
mi = int(len(str1) / 2)
res = str1[mi - 1:mi + 2]
print("Middle three chars are:", res)

get_middle_three_chars(“Hyderabad")
get_middle_three_chars(“Bangalore")
Given two strings, s1 and s2. Write a program to create a new string s3 by appending
s2 in the middle of s1.
I/P:
Original Strings are Shriyaan Ram
O/P:
After appending new string in middle: ShriRamyaan
def append_middle(s1, s2):
print("Original Strings are", s1, s2)
mi = int(len(s1) / 2)
x = s1[:mi]
x = x + s2
x = x + s1[mi:]
print("After appending new string in middle:", x)

append_middle(“Shriyaan", “Ram")
Given two strings, s1 and s2, write a program to return a new string made of s1 and
s2’s first, middle, and last characters.
I/P:
s1 = "America"
s2 = "Japan“

O/P: AJrpan
def mix_string(s1, s2):
first_char = s1[0] + s2[0]
middle_char = s1[int(len(s1) / 2)] + s2[int(len(s2) / 2)]
last_char = s1[len(s1) - 1] + s2[len(s2) - 1]
res = first_char + middle_char + last_char
print("Mix String is ", res)

s1 = "America"
s2 = "Japan"
mix_string(s1, s2)
Given string contains a combination of the lower and upper case
letters. Write a program to arrange the characters of a string so that
all lowercase letters should come first.
i/p:
str1 = GPreC

o/p: reGPC
str1 = "GPreC"
print('Original String:', str1)
lower = []
upper = []
for char in str1:
if char.islower():
lower.append(char)
else:
upper.append(char)

sorted_str = ''.join(lower + upper)


print('Result:', sorted_str)
Count all letters, digits, and special symbols from a given string

i/p: str1 = "P@#yn26at^&i5ve“


o/p:
Chars = 8
Digits = 3
Symbol = 4
def find_digits_chars_symbols(sample_str):
char_count = 0
digit_count = 0
symbol_count = 0
for char in sample_str:
if char.isalpha():
char_count += 1
elif char.isdigit():
digit_count += 1
# if it is not letter or digit then it is special symbol
else:
symbol_count += 1
print("Chars =", char_count, "Digits =", digit_count, "Symbol =", symbol_count)
sample_str = "P@yn2at&#i5ve"
print("total counts of chars, Digits, and symbols \n")
find_digits_chars_symbols(sample_str)
Given a string s1, write a program to return the sum and average of the digits that
appear in the string, ignoring all other characters.

i/p: str1 = "Pythonclass29@#8496“

o/p: Sum is: 38


Average is 6.333333333333333
input_str = "Pythonclass29@#8496"
total = 0
cnt = 0
for char in input_str:
if char.isdigit():
total += int(char)
cnt += 1

avg = total / cnt


print("Sum is:", total, "Average is ", avg)
Write a program to split a given string on hyphens and display each substring
i/p: Shriyaan-is-a-data-scientist
o/p:
Shriyaan
is
a
data
scientist
str1 = "Shriyaan-is-a-data-scientist"
print("Original String is:", str1)
sub_strings = str1.split("-")
print("Displaying each substring")
for sub in sub_strings:
print(sub)
Write a program to display the largest word in the given string
str=input(“enter any string”)
L=str.split()
max=0
b=“ ”
for i in L:
if len(i)>max:
b=i
max=len(i)
Print (“longest word is”,b)
Write a Python program to remove duplicate words from a given string
str = "Python Exercises Practice Solution Exercises"
l = str.split()
temp = []
for x in l:
if x not in temp:
temp.append(x)
print("After Removing Duplicates :\n\t",' '.join(temp))
Write a Python program to swap cases of a given string
str="professor Shriyaan Computer Education"
res = ""
for ch in str:
if ch.isupper():
res += ch.lower()
else:
res += ch.upper()
print(res)
ch='p'
str="professor Shriyaan Computer programmer"
print("Original String :",str)
res = str.replace(ch, "")
print("Delete All Occurrences Specified Given
String :",res)
Write a Python function to convert a given string to all
uppercase if it contains at least 2 uppercase characters in
the first 4 characters
str = input("Enter the String :")
num_upper = 0
for letter in str[:4]:
if letter.isupper():
num_upper += 1
if num_upper >= 2:
print(str.upper())
else:
print(str)
Write a Python function to reverses a string if its length is a
multiple of 4
str=input("Enter the String :")
if len(str) % 4 == 0:
print(str[::-1])
else:
print(str)

You might also like