0% found this document useful (0 votes)
115 views20 pages

7 String

1. Python treats any sequence of characters within single or double quotes as a string. Strings can be accessed using indexes or slices and various string methods like find, count, replace, split can be used to manipulate strings. 2. Mathematical operators like + and * can be used to concatenate and repeat strings. Various functions like len(), upper(), lower() etc. are available to get string length or change case. 3. Membership, comparison and other operations are also supported on strings in Python.

Uploaded by

Vasantha Peram
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)
115 views20 pages

7 String

1. Python treats any sequence of characters within single or double quotes as a string. Strings can be accessed using indexes or slices and various string methods like find, count, replace, split can be used to manipulate strings. 2. Mathematical operators like + and * can be used to concatenate and repeat strings. Various functions like len(), upper(), lower() etc. are available to get string length or change case. 3. Membership, comparison and other operations are also supported on strings in Python.

Uploaded by

Vasantha Peram
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/ 20

Python

String:
Any sequence of characters within double quotes or single quotes is
considered as a string.
Ex:
>>>s="HareKrishna"
>>>type(s)
<class ‘str’>
>>>ch='a'
>>>type(ch)
<class ‘str’>
In Python, string literals are enclosed in single quotes or double quotes.
Multiline strings: -
If you want to assign multiline strings then we use triple single quotes or triple
double quotes.
Ex:
>>>s='''krishna
Software
Solutions'''
>>>print(s)

To use single quote or double quotes as symbol in string literal.


Ex:
>>>s1="Python is ‘simple’ and easy language"
>>>print(s1)
>>>s2='Python is “simple” and easy language'
>>>print(s2)
>>>s3="Python is \‘simple\’ and \“easy\” language"
>>>print(s3)
>>>s4="""Python is ‘simple’ and “easy” language"""
>>>print(s4)
>>>s5='''Python is ‘simple’ and “easy” language'''
>>>print(s5)
1
Python

Accessing characters in string:


1. By using index
2. By using slice operator
Accessing characters using index:
Python supports both positive and negative indexes.
 +ve index means Left to Right (Forward direction).
 -ve index means Right to Left (Backward direction).

s=’ramana’
0 1 2 3 4 5
r a m a n a
-6 -5 -4 -3 -2 -1

>>>s[2]
m
>>>s[-3]
a
>>>s[10]
IndexError: string index out of range.

Ex: Accept a string from the keyboard and display each character and its
positive and negative index.
s=input("Enter some string:")
i=0
for x in s:
print("The character at positive index { } and at negative index { } is { }"
.format(i,i-len(s),x))
i=i+1

Accessing characters by using slice operator:


Syntax:
stringvariable[beginindex:endindex:step]
2
Python

beginindex: From where we have to consider slice (substring).


endindex: We have to terminate the slice(substring) at endindex-1.
step: Incremented value.
Note:
. If we are not specifying begin index then it will consider from beginning of the
string.
. If we are not specifying end index then it will consider upto end of the string.
. The default for step value is 1.
Ex:
>>>s='Python is simple language'
>>>print(s[2:6])
output: thon
>>>print(s[2:16:2])
output: to ssml
>>>print(s[:16])
output: Python is simple
>>>print(s[3:])
output: hon is simple language
>>>print(s[::-1])
output: egaugnal elpmis si nohtyP

Ex:
str="Learning python is very very easy"
b=int(input("Enter begin index:"))
e=int(input("Enter end index:"))
s=int(input("Enter step value:"))
print(str[b:e:s])

Behavior of slice operator:


s[begin:end:step]
step value can be either positive or negative.
If it is positive we have to consider in forward direction from begin to end-1.
3
Python

If it is negative then we have to consider in backward direction from begin to end+1.
In forward direction if end value is 0 then result is always empty.
In backward direction if end value is -1 then result is always empty.
Ex:
>>>s='abcdefghij'
>>>s[1:6:2] 'bdf'
>>>s[::1] 'abcdefghij'
>>>s[::-1] 'jihgfedcba'
>>>s[3:7:-1] ''
>>>s[7:4:-1] 'hgf'
>>>s[0:10000:1] 'abcdefghij'
>>>s[-4:1:-1] 'gfedc'
>>>s[-4:1:-2] 'gec'
>>>s[5:0:1] ''
>>>s[9:0:0] ValueError: slice step cannot be zero
>>>s[0:-10:-1] ''
>>>s[0:-11:-1] 'a'
>>>s[0:0:1] ''
>>>s[0:-9:-2] 'bdf'
>>>s[-5:-9:-2] 'fd'
>>>s[10:-1:-1] ''
>>>s[10000:2:-1] 'jihgfed'
Note: slice operator never raises IndexError.

Mathematical operators for string:


We can apply the following mathematical operators for strings.
1. + operator for concatenation.
2. * operator for repetition.
Ex:
>>>print("Hare"+"Krishna") HareKrishna
>>>print("Krishna"*2) KrishnaKrishna

4
Python

Note:
. To use + operator for strings, compulsory both arguments should be str type.
. To use * operator for strings, compulsory one argument should be str and other
argument should be int.
Ex:
str1 = 'Hello'
str2 ='World!'
# using +
print(str1 + str2)
# using *
print(str1 * 3)
print(2 * str1 )

len(): - This function is used to find the number of characters present in the string.
Ex:
s='krishna'
len(s) 7

Ex: Write a program to display string in forward and backward directions


using while loop.
s=input("Enter string:")
i=0
n=len(s)
print("Forward direction:")
while i<n:
print(s[i],end='')
i=i+1
print()
print("Backward direction:")
i=-1
while i>=-n:

5
Python

print(s[i],end='')
i=i-1

Using for loop


s=input("Enter string:")
print("Forward direction:")
for x in s
print(x,end='')
print("Forward direction:")
for x in s[::]:
print(x,end='')
print("Backward direction:")
for x in s[::-1]:
print(x,end='')

Ex: String Concatenation.


s1=input("Enter string:")
s2=input("Enter string:")
s3=s1+s2
print(s3)

Ex: To display string n number of times.


s1=input("Enter string:")
n=int(input("Enter no to display:"))
print(s1*n)

Ex: Comparing strings


s1=input("Enter first string:")
s2=input("Enter second string:") if
s1==s2:
print("Both strings are equal")
elif s1>s2:
6
Python

print("String1 is big")
else:
print("String2 is big")

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.
in operator returns True if the substring is available otherwise it returns False.
not in operator returns False if the substring is available otherwise it returns True.
Ex:
s='krishna'
print('i' in s) #True
print('b' in s) #False

Ex:
s=input("Enter main string:")
sub=input("Enter sub string:") if
sub in s:
print("substring is available in main string")
else:
print("substring is not available in main string")

Finding sub strings:


find() Forward direction
index()
rfind() Backward direction
rindex()

find(): - It returns index of first occurrence of the given substring. If it is not


available then it returns -1.

7
Python

Syntax1:
String.find(substring)
Ex:
s="Learning python is very easy"
print(s.find('python')) #9
print(s.find('java')) #-1

Syntax2:
String.find(substring,start,end)
Ex:
s="Learning python is very easy"
print(s.find('h',2,10))

rfind(): - It searches from right to left. It returns index of substring at first


occurrence of given substring. If it is not available then it returns -1.
Syntax:
string.rfind(substring)
Ex:
s="Learning python is very easy"
print(s.rfind('e'))

index(): - It is exactly same as find() function except that if the specified


substring is not available then we will get ValueError.
Syntax:
String.index(substring)
Ex:
s="Learning python is very easy"
print(s.index('python'))
print(s.index('java'))

rindex(): - It is same as rfind() function but this method returns ValueError if


string is not available.
8
Python

Syntax:
string.rindex(substring)
Ex:
s="Learning python is very easy"
print(s.rindex('h'))

Ex: Display all occurrences of sub string.


s=input("Enter some string:")
sub=input("Enter sub string:")
pos=-1
n=len(s)
count=0
while True:
pos=s.find(sub,pos+1,n) if
pos==-1:
break
print("Found at position:",pos)
count=count+1
if count==0:
print("Substring not found")
else:
print("The number of occurrences =",count)

Counting substrings:
count(): This function is used to counting the substring in the given string.
Syntax:
string.count(substring)
string.count(substring,begin,end)
Ex:
s='satish software solutions'
print(s.count('s'))

9
Python

Ex:
s='abababbabaab' sub='b'
print("The no of occurrences:",s.count(sub))
print("The no of occurrences:",s.count(sub,5,10))

Replacing a string with another string:


replace(): - This function is used to replace the new string in place of old
string.
Syntax:
string.replace(oldstring, newstring)
Ex:
s='abababba'
print(s.replace('a','b'))

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.

Ex: Dividing string into substrings according to space.


s='satish software solutions'
list=s.split()
print(list)
for x in list:
print(x)
Ex: Split according to character
s='10-06-2018'
list=s.split('-')
for x in list:
print(x);

10
Python

Join substrings into string


join(): - This function is used to join the substrings into one string.
Syntax:
separator.join(substrings)
Ex:
l=['satish','lokesh','rajesh','lohit']
s='-'.join(l)
print(s)

Change case of string:


upper(): - This function is used to convert all characters into uppercase. lower(): -
This function is used to convert all characters into lowercase. swapcase(): - This
function is used to convert all upper case characters into lowercase and vice versa.
title(): - This function is used to convert each and every word of first character
converted into uppercase cahracter.
capitalize(): - This function is used to convert first character of each sentence
into uppercase.

Ex:
s="learning Python is very easy"
print(s.upper())
print(s.lower())
print(s.swapcase()) print(s.title())
print(s.capitalize())

To check starting and ending positions


startswith(): - This function is used to find the given string is starting with
specified string.
endswith(): - This function is used to find the given string is ending with
specified string.

11
Python

Ex:
s="learning Python is very easy"
print(s.startswith("learning"))
print(s.startswith("teaching"))
print(s.endswith("easy"))

To check type of characters present in the string:


isalnum(): - To check whether the character is alpha-numeric character or not.
isalpha(): - To check whether the character is alphabet or not.
isdigit(): - To check whether the character is number or not.
islower(): - To check whether the character or string in lower case or not. isupper():
- To check whether the character or string in upper case or not. istitle(): - To check
whether the each word first character in upper case or not. isspace(): - To check
whether the character is space or not.
Ex:
print("rama8234".isalnum()) #True
print("satish$8234".isalnum()) #False
print("rama".isalpha()) #True
print("rama".isdigit()) #False
print("Learning Python Is Very Easy".istitle()) #True
print(" ".isspace()) #True

Ex: Accept a character and display character type.


If character type is alpha numeric then recognize alphabet or digit.
If alphabet then recognize capital letter or small letter.

s=input("Enter any character:") if


s.isalnum():
print("Alpha-numeric character") if
s.isalpha():
print("Alphabet character")

12
Python

if s.islower():
print("Lower case character")
else:
print("Upper case character")
else:
print("Digit"
) elif s.isspace():
print("Space character")
else:
print("Non space special character")

Ex: Write a program to reverse the given string.


s=input("Enter any string:")
print(s[::-1])

without slice operator:


s=input("Enter any string:")
for x in reversed(s):
print(x)
#print(''.join(reversed(s))

Using while loop:


s=input("Enter any string:")
i=len(s)-1
target=' '
while i>=0:
target=target+s[i]
i=i-1
print(target)

Using for loop:


s=input("Enter any string:")
13
Python

target=' '
for I in range(len(s)-1,0,-1):
target=target+s[i]
print(target)

Ex: Write a program to reverse of words


s=input("Enter some string")
l=s.split();
l1=[]
i=len(l)-1
while i>=0:
l1.append(l[i])
i=i-1
out=' '.join(l1)
print(out)

another way
s=input("Enter some string")
l=s.split();
l1=[]
for i in range(len(l)):
s1=s[i]
l1.append(s1[::-1])
print(l1)
out=' '.join(l1)
print(out)

another way
s=input("Enter some string")
l=s.split();
l1=[]
for x in l:
14
Python

l1.append(x[::-1])
out=' '.join(l1)
print(out)

Ex: Write a program to reverse of internal content of each word


s=input("Enter some string")
l=s.split();
l1=[]
i=0
i=len(l)-1
while i<len(i):
l1.append(l[i][::-1])
i=i-1
out=' '.join(l1)
print(out)

Ex: To print characters at odd position and even position


s=input("Enter some string") print("Character at
even position:",s[:2]) print("Character at odd
position:",s[1::2])

another way
s=input("Enter some string") i=0
print("Character at even position:")
while(i<len(s)):
print(s[i],end=',')
i=i+2
print("Character at odd position:")
i=1

while(i<len(s)):

15
Python

print(s[i],end=',')
i=i+2

Ex: Accept two strings and merge one by one character


s1=input("Enter first string:")
s2=input("Enter second string:") output=' '
i,j=0,0
while i<len(s1) or j<len(s2):
output=output+s1[i]
i=i+1
output=output+s2[j]
j=j+1
print(output)

The above program works only for same length strings to solve the
following code.
s1=input("Enter first string:")
s2=input("Enter second string:") output=' '
i,j=0
while i<len(s1) or j<len(s2):
if i<len(s1):
output=output+s1[i]
i=i+1
if j<len(s2):
output=output+s2[j]
j=j+1
print(output)

16
Python

Ex: To sort character of the string, first alphabets followed by


numeric values.
Input: satish8234
Output: ahisst2348
s=input("Enter some string:")
s1=s2=output=' '
for x in s:
if x.isalpha():
s1=s1+x
else:

s2=s2+x
print(s1)
print(s2)
for x in sorted(s1):
output=output+x
for x in sorted(s2):
output=output+x
print(output)
#print(' '.join(sorted(s1)+ ' '.join(sorted(s2))

Ex: Enter string by character with number and display each character
specified number of times.
Input: a4c3b2
Output: aaaacccbb
s=input("Enter some string:")
output=' '
for x in s:
if x.isalpha():
previous=x
else:

output=output+(previous*(int(x))
print(output)

17
Python

Ex: Enter a string to print character and number of


times Input: aaaaakkkbb
Output: a5k3b2
s=input("Enter first string:")
output=''
i=0
while i<len(s):
temp=s[i]
output=output+temp
c=0
while i<len(s):
if temp==s[i]:
c=c+1
i=i+1
else:
break
output=output+str(c)
print(output)

Ex: Enter string display each number with specified alphabet character.
Input: a4k3b2
Output: aeknbd
chr(unicode)  It provides character
ord(character)  It provides Unicode value

s=input("Enter some string:")


output=' '
for x in s:
if x.isalpha():
output=output+x
previous=x
else:
18
Python

output=output+chr(ord(previous)+int(x))
print(output)

Ex: Enter string display string without duplicate characters.


Input: ABCABCAAABCAD
Output: ABCD
s=input("Enter some string:")
l=[]
for x in s:
if x not in l:
l.append(x)
output=' '.join(l)
print(output)

Another way
s=input("Enter some string:")
output=' '
for x in s:
if x not in output:
output=output+x
print(output)

Ex: Write a program to find the number of occurrences of each character


present in the given string.
Input: ABCABCABBCDE
Output: A-3,B-4,C-3,D-1,E-1
s=input("Enter some string:")
d={}
for x in s:
if x in d.keys():
d[x]=d[x]+1

else:
19
Python

d[x]=1
for k,v in d.items():
print("{}={} Times".format(k,v))

20

You might also like