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

String in Python

Uploaded by

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

String in Python

Uploaded by

oppoa33fmc
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

CHAPTER-6

STRING IN PYTHON

6.1 Introduction:
Definition: Sequence of characters enclosed in single, double or triple quotation marks.
Basics of String:
 Strings are immutable in python. It means it is unchangeable. At the same memory
address, the new value cannot be stored.

 Each character has its index or can be accessed using its index.

 String in python has two-way index for each location. (0, 1, 2, ……. In the forward
direction and -1, -2, -3, …….. in the backward direction.)
Example:
0 1 2 3 4 5 6 7
k e n d r i y a
-8 -7 -6 -5 -4 -3 -2 -1

 The index of string in forward direction starts from 0 and in backward direction starts
from -1.
 The size of string is total number of characters present in the string. (If there are n
characters in the string, then last index in forward direction would be n-1 and last index
in backward direction would be –n.)

 String are stored each character in contiguous location.


 The character assignment is not supported in string because strings are immutable.
Example :
str = “kendriya”
str[2] = ‘y’ # it is invalid. Individual letter assignment not allowed in python

6.2 Traversing a String:


Access the elements of string, one character at a time.
str = “kendriya”
for ch in str :
print(ch, end= ‘ ‘)

[Link] Page 50
Output:
kendriya

6.3 String Operators:


a. Basic Operators (+, *)
b. Membership Operators ( in, not in)
c. Comparison Operators (==, !=, <, <=, >, >=)

a. Basic Operators: There are two basic operators of strings:


i. String concatenation Operator (+)
ii. String repetition Operator (*)

i. String concatenation Operator: The + operator creates a new string by joining the two
operand strings.
Example:
>>>”Hello”+”Python”
‘HelloPython’
>>>’2’+’7’
’27’
>>>”Python”+”3.0”
‘Python3.0’

Note: You cannot concate numbers and strings as operands with + operator.
Example:
>>>7+’4’ # unsupported operand type(s) for +: 'int' and 'str'
It is invalid and generates an error.

[Link] Page 51
ii. String repetition Operator: It is also known as String replication operator. It requires
two types of operands- a string and an integer number.
Example:
>>>”you” * 3
‘youyouyou’
>>>3*”you”
‘youyouyou’

Note:You cannot have strings as n=both the operands with * operator.


Example:
>>>”you” * “you” # can't multiply sequence by non-int of type 'str'
It is invalid and generates an error.

b. Membership Operators:
in – Returns True if a character or a substring exists in the given string; otherwise False
not in - Returns True if a character or a substring does not exist in the given string; otherwise False

Example:
>>> "ken" in "Kendriya Vidyalaya"
False
>>> "Ken" in "Kendriya Vidyalaya"
True
>>>"ya V" in "Kendriya Vidyalaya"
True
>>>"8765" not in "9876543"
False

c. Comparison Operators: These operators compare two strings character by character


according to their ASCII value.

[Link] Page 52
Characters ASCII (Ordinal) Value

‘0’ to ‘9’ 48 to 57

‘A’ to ‘Z’ 65 to 90

‘a’ to ‘z’ 97 to 122

Example:
>>> 'abc'>'abcD'
False
>>> 'ABC'<'abc'
True
>>> 'abcd'>'aBcD'
True
>>> 'aBcD'<='abCd'
True

6.4 Finding the Ordinal or Unicode value of a character:


Function Description
ord(<character>) Returns ordinal value of a character

chr(<value>) Returns the corresponding character

Example:
>>> ord('b')
98
>>> chr(65)
'A'

[Link] Page 53
Program: Write a program to display ASCII code of a character and vice versa.
var=True
while var:
choice=int(input("Press-1 to find the ordinal value \n Press-2 to find a character of a value\n"))
if choice==1:
ch=input("Enter a character : ")
print(ord(ch))
elif choice==2:
val=int(input("Enter an integer value: "))
print(chr(val))
else:
print("You entered wrong choice")

print("Do you want to continue? Y/N")


option=input()
if option=='y' or option=='Y':
var=True
else:
var=False

6.5 Slice operator with Strings:


The slice operator slices a string using a range of indices.
Syntax:
string-name[start:end]
where start and end are integer indices. It returns a string from the index start to end-1.
0 1 2 3 4 5 6 7 8 9 10 11 12 13
d a t a s t r u c t u r e
-14 -13 -12 -11 -10 -9 -8 -7 -6 -5 -4 -3 -2 -1

[Link] Page 54
Example:
>>> str="data structure"
>>> str[0:14]
'data structure'
>>> str[0:6]
'data s'
>>> str[2:7]
'ta st'
>>> str[-13:-6]
'ata str'
>>> str[-5:-11]
'' #returns empty string
>>> str[:14] # Missing index before colon is considered as 0.
'data structure'
>>> str[0:] # Missing index after colon is considered as 14. (length of string)
'data structure'
>>> str[7:]
'ructure'
>>> str[4:]+str[:4]
' structuredata'
>>> str[:4]+str[4:] #for any index str[:n]+str[n:] returns original string
'data structure'
>>> str[8:]+str[:8]
'ucturedata str'
>>> str[8:], str[:8]
('ucture', 'data str')
Slice operator with step index:
Slice operator with strings may have third index. Which is known as step. It is optional.

[Link] Page 55
Syntax:
string-name[start:end:step]
Example:
>>> str="data structure"
>>> str[2:9:2]
't tu'
>>> str[-11:-3:3]
'atc'
>>> str[: : -1] # reverses a string
'erutcurts atad'

Interesting Fact: Index out of bounds causes error with strings but slicing a string outside the
index does not cause an error.
Example:
>>>str[14]
IndexError: string index out of range
>>> str[14:20] # both indices are outside the bounds
' ' # returns empty string
>>> str[10:16]
'ture'

Reason: When you use an index, you are accessing a particular character of a string, thus the
index must be valid and out of bounds index causes an error as there is no character to return
from the given index.
But slicing always returns a substring or empty string, which is valid sequence.

6.6 Built-in functions of string:


Example:
str=”data structure”

[Link] Page 56
s1= “hello365”
s2= “python”
s3 = ‘4567’
s4 = ‘ ‘
s5= ‘comp34%@’
S. No. Function Description Example
1 len( ) Returns the length of a string >>>print(len(str))
14
2 capitalize( ) Returns a string with its first character >>> [Link]()
capitalized. 'Data structure'
3 find(sub,start,end) Returns the lowest index in the string where the >>> [Link]("ruct",5,13)
substring sub is found within the slice range. 7
Returns -1 if sub is not found. >>> [Link]("ruct",8,13)
-1
4 isalnum( ) Returns True if the characters in the string are >>>[Link]( )
alphabets or numbers. False otherwise True
>>>[Link]( )
True
>>>[Link]( )
True
>>>[Link]( )
False
>>>[Link]( )
False
5 isalpha( ) Returns True if all characters in the string are >>>[Link]( )
alphabetic. False otherwise. False
>>>[Link]( )
True
>>>[Link]( )
False
>>>[Link]( )
False
>>>[Link]( )
False
6 isdigit( ) Returns True if all the characters in the string are >>>[Link]( )
digits. False otherwise. False
>>>[Link]( )
False
>>>[Link]( )
True
>>>[Link]( )
False
>>>[Link]( )
False
7 islower( ) Returns True if all the characters in the string are >>> [Link]()
lowercase. False otherwise. True
>>> [Link]()

[Link] Page 57
True
>>> [Link]()
False
>>> [Link]()
False
>>> [Link]()
True
8 isupper( ) Returns True if all the characters in the string are >>> [Link]()
uppercase. False otherwise. False
>>> [Link]()
False
>>> [Link]()
False
>>> [Link]()
False
>>> [Link]()
False
9 isspace( ) Returns True if there are only whitespace >>> " ".isspace()
characters in the string. False otherwise. True
>>> "".isspace()
False
10 lower( ) Converts a string in lowercase characters. >>> "HeLlo".lower()
'hello'
11 upper( ) Converts a string in uppercase characters. >>> "hello".upper()
'HELLO'
12 lstrip( ) Returns a string after removing the leading >>> str="data structure"
characters. (Left side). >>> [Link]('dat')
if used without any argument, it removes the ' structure'
leading whitespaces. >>> [Link]('data')
' structure'
>>> [Link]('at')
'data structure'
>>> [Link]('adt')
' structure'
>>> [Link]('tad')
' structure'
13 rstrip( ) Returns a string after removing the trailing >>> [Link]('eur')
characters. (Right side). 'data struct'
if used without any argument, it removes the >>> [Link]('rut')
trailing whitespaces. 'data structure'
>>> [Link]('tucers')
'data '
14 split( ) breaks a string into words and creates a list out of it >>> str="Data Structure"
>>> [Link]( )
['Data', 'Structure']

[Link] Page 58
Programs related to Strings:
1. Write a program that takes a string with multiple words and then capitalize the first
letter of each word and forms a new string out of it.
Solution:
s1=input("Enter a string : ")
length=len(s1)
a=0
end=length
s2="" #empty string
while a<length:
if a==0:
s2=s2+s1[0].upper()
a+=1
elif (s1[a]==' 'and s1[a+1]!=''):
s2=s2+s1[a]
s2=s2+s1[a+1].upper()
a+=2
else:
s2=s2+s1[a]
a+=1
print("Original string : ", s1)
print("Capitalized wrds string: ", s2)

2. Write a program that reads a string and checks whether it is a palindrome string or
not.
str=input("Enter a string : ")
n=len(str)
mid=n//2
rev=-1

[Link] Page 59
for i in range(mid):
if str[i]==str[rev]:
i=i+1
rev=rev-1
else:
print("String is not palindrome")
break
else:
print("String is palindrome")

3. Write a program to convert lowercase alphabet into uppercase and vice versa.
choice=int(input("Press-1 to convert in lowercase\n Press-2 to convert in uppercase\n"))
str=input("Enter a string: ")
if choice==1:
s1=[Link]()
print(s1)
elif choice==2:
s1=[Link]()
print(s1)
else:
print("Invalid choice entered")

[Link] Page 60

You might also like