[go: up one dir, main page]

0% found this document useful (0 votes)
8 views14 pages

CH 8 Strings

The document provides a comprehensive overview of strings in Python, covering their definition, properties, and various operations including indexing, slicing, and built-in functions. It explains string immutability, operators for concatenation and repetition, as well as membership and comparison operators. Additionally, it includes examples of string manipulation programs such as counting characters, checking for palindromes, and converting character cases.

Uploaded by

ai.crimson158
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)
8 views14 pages

CH 8 Strings

The document provides a comprehensive overview of strings in Python, covering their definition, properties, and various operations including indexing, slicing, and built-in functions. It explains string immutability, operators for concatenation and repetition, as well as membership and comparison operators. Additionally, it includes examples of string manipulation programs such as counting characters, checking for palindromes, and converting character cases.

Uploaded by

ai.crimson158
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
You are on page 1/ 14

CH-8 STRINGS

Introduction
Definition: Sequence of characters enclosed in single, double or triple quotation marks.
Eg. str1=’PYTHON’
str2=”PYTHON”
str3=’’’PYTHON’’’
str4=”””PYTHON”””

Basics of Strings
❖ Strings are immutable in Python. This 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 and is written in square
brackets([ ]).
Eg.

❖ Index Error: Index value out of range. Eg. str[6]


❖ Index must be an integer(positive, zero or negative)
❖ Strings are stored each character in contiguous location.
❖ The size of string is the total number of characters present in the string.
An inbuilt function len() is used to return the length of the string.
Eg. str1=”HELLO”
>>> len(str1)
5
Eg. str1=”HELLO WORLD”
>>>len(str1)
11
❖ String in Python has a two-way index for each location.
➢ Forward Indices: The index of string in forward direction starts from 0 and
last index is n-1(0,1,2,……)from left to right.
➢ Backward Indices: The index of string in backward direction starts from -1
and last index is -n(-1,-2,-3….) from right to left.

Eg. str1=”HELLO WORLD”


Forward Indexing

Backward Indexing

>>> str1[0]
‘H’
>>>str1[6]
‘W’
>>>str1[-10]
‘e’
>>>str1[11]
Index Error: String out of range
>>>str1[1+5]
‘W’
>>>str1[1.5]
Type Error: String indices must be an integer.
>>>str1[-n]
‘H’
>>>str1[n-1]
‘d’
❖ Character assignment is not supported in string because strings are immutable.
Eg. str1=”HELLO”
str1[2]=”A”
# It is invalid. Individual letter assignment not allowed in Python.

STRING OPERATORS
1. Basic Operators(+,*)
2. Membership Operators(in, not in)
3. Comparison Operators(==,!=,<,<=,>,>=)
4. Slicing

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


a. String Concatenation operator(+)
b. String Repetition operator(*)
a. String Concatenation Operator: Concatenation means to join. The ‘+’ operator creates
a new string by joining the two string operands.
Eg. >>> “Hello”+”World”
‘HelloWorld’
>>> “PYTHON”+”3.0”
‘PYTHON3.0’
Note: You cannot concatenate numbers and strings as operands with + operator.
Eg. >>>7+’4’ # unsupported operand type(s) for +, ‘int’ and ‘string’.
It is invalid and generates an error.

b. String Repetition Operator: It is also known as string replication operator. It requires


two types of operands – a string and an integer number.
Eg. >>> “Hello”*3
‘HelloHelloHello’
>>> 4*”Python”
‘PythonPythonPythonPython’
Note: You cannot have strings as both the operands with * operator.
Eg, >>>”Hello”*”World” # Cannot multiply sequence by non-int of type ‘str’
It is invalid and generates an error
2. Membership Operators
a. in operator- Returns True if a character on a substring exists in the given string.
Otherwise False.
b. Not in operator-Returns True if a character or a substring does not exist in the given
string. Otherwise False.
Eg. >>>”hell” in “Hello World”
False
>>>”lo Wor” in “Hello World”
True
>>>”Hi” not in “Hello World”
True
>>>”1234” not in”98123456”
False
3. Comparison Operators
These Operators compare two strings, character by character according to their ASCII value.

Character ASCII (Ordinal) Values


‘0’ to ‘9’ 48 to 57

‘A’ to ‘Z’ 65 to 90

‘a’ to ‘z’ 97 to 122

Eg. >>> ‘abc’>’abcD’


False
>>>’ABC’<’abc’
True
>>>’abcd’>’aBcD’
True
>>>’aBcD’<=’abCd’
True

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
Eg. >>>ord(‘b’)
98
>>>chr(65)
‘A’

4. String Slicing
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.
Eg.

>>> str1=”Hello World”

>>>str1[0:11]

‘Hello World’

>>>str1[0:7]

‘Hello W’

>>>str1[-5:-1]

‘Worl

>>>str1[:5]

‘Hello’

>>>str1[6:]

‘World’

>>>str1[-11:-6]

‘Hello’

>>> str1[::-1] # string is obtained in the reverse order

‘dlrow olleH’

>>> str1[5:] + str1[:5]

‘WorldHello’
>>>str1[8:]+str1[:8]

‘rldHello Wo’

Slice Operator with step index: Slice operator with strings may have third index which is known as step, it
is optional.

Syntax:

String_name[Start:End:Step]

Eg. >>>str1=”Hello World”

>>>str1[2:9:2]

‘loWr’

>>>str[-11,-3,3]

‘HlW

Note: In Slicing a string outside the index doesn’t cause index error.

Eg. >>>str1[14]

Index Error(Out of range)

>>>str1[8:16]

rld

Note: When you are accessing a particular character, index must be valid .If it is out of bound, an index
error will show. But in slicing, it returns a substring or empty string which is valid in sequence.

Traversing a String
We can access each character of a string or traverse a string using for loop and while loop.

(A) String Traversal Using for Loop:

>>> str1 = 'Hello World!'

>>> for ch in str1:

print(ch,end = “”)

Hello World! #output of for loop

In the above code, the loop starts from the first character of the string str1 and automatically ends

when the last character is accessed.

(B) String Traversal Using while Loop:

>>> str1 = 'Hello World!'

>>> index = 0

#len(): a function to get length of string


>>> while index < len(str1):

print(str1[index],end = '')

index += 1

Hello World! #output of while loop

Here while loop runs till the condition index < len(str) is True, where index varies from 0 to len(str1) -1.

Built in Functions
Function Name Description Example
len() Returns length of the string >>> str1 = 'Hello World!'
>>> len(str1)
12
capitalize() Converts the first character of the >>> str1 = 'hello World!'
string to a capital (uppercase) letter >>> str1.capitalize()
‘Hello World!’
title() Convert string to title case >>> str1 = 'hello WORLD!'
>>> str1.title()
'Hello World!'
lower() Converts all uppercase characters in a >>> str1 = 'hello WORLD!'
string into lowercase >>> str1.lower()
'hello world!'
upper() Converts all lowercase characters in a >>> str1 = 'hello WORLD!'
string into uppercase >>> str1.upper()
'HELLO WORLD!'
count(str,start,end) Returns the number of occurrences of >>> str1 = 'Hello World! Hello
a substring in the string. Hello'
>>> str1.count('Hello',12,25)
2
>>> str1.count('Hello')
3
find(str,start,end) Returns the lowest index of the >>> str1 = 'Hello World! Hello
substring if it is found otherwise Hello'
returns -1. >>> str1.find('Hello',10,20)
13
>>> str1.find('Hello',15,25)
19
>>> str1.find('Hello')
0
>>> str1.find('Hee')
-1
index(str,start,end) Returns the position of the first >>> str1 = 'Hello World! Hello
occurrence of a substring in a string Hello'
>>> str1.index('Hello')
0
>>> str1.index('Hee')
ValueError: substring not found
endswith() Returns “True” if a string ends with >>> str1 = 'Hello World!'
the given suffix
>>> str1.endswith('World!')
True
>>> str1.endswith('lde')
False
Startswith() Returns True if the given string starts >>> str1 = 'Hello World!'
with the supplied substring otherwise >>> str1.startswith('He')
returns False True
>>> str1.startswith('Hee')
False
isalnum() Checks whether all the characters in a >>> str1 = 'HelloWorld'
given string is alphanumeric or not >>> str1.isalnum()
True
>>> str1 = 'HelloWorld!!'
>>> str1.isalnum()
False
isalpha() Returns “True” if all characters in the >>> str1 = 'HelloWorld'
string are alphabets >>> str1.isalpha()
True
isdigit() Returns “True” if all characters in the >>> str1 = 'HelloWorld'
string are digits >>> str1.isdigit()
False
>>>str2=’123’
>>>str2.isdigit()
True
islower() Checks if all characters in the string >>> str1 = 'hello world!'
are lowercase >>> str1.islower()
True
>>> str1 = '1234'
>>> str1.islower()
False

isupper() Checks if all characters in the string >>> str1 = 'HELLO WORLD!'
are uppercase >>> str1.isupper()
True
>>> str1 = '1234'
>>> str1.isupper()
False

isspace() Returns “True” if all characters in the >>> str1 = ' \n \t \r'
string are whitespace characters >>> str1.isspace()
True
>>> str1 = 'Hello \n'
>>> str1.isspace()
False
istitle() Returns True if the string is non- >>> str1 = 'Hello World!'
empty and title case, i.e., the first >>> str1.istitle()
letter of every word in the string in True
uppercase and rest in lowercase >>> str1 = 'hello World!'
>>> str1.istitle()
False
lstrip() Returns the string after removing the >>> str1 = ' Hello World! '
spaces only on the left of the string >>> str1.lstrip()
'Hello World! ‘
rstrip() Returns the string after removing the >>> str1 = ' Hello World! '
spaces only on the right of the string >>> str1.rstrip()
' Hello World!'
strip() Returns the string after removing the >>> str1 = ' Hello World! '
spaces both on the left and the right >>> str1.strip()
of the string 'Hello World!'
replace(oldstr,newstr) Replaces all occurrences of a >>> str1 = 'Hello World!'
substring with another substring >>> str1.replace('o','*')
'Hell* W*rld!'
join() Returns a concatenated String >>> str1 = ('HelloWorld!')
>>> str2 = '-' #separator
>>> str2.join(str1)
'H-e-l-l-o-W-o-r-l-d-!'
partition() Partitions the given string at the >>> str1 = 'India is a Great
first occurrence of the substring Country'
(separator) and returns the string >>> str1.partition('is')
partitioned into three parts. ('India ', 'is', ' a Great Country')
1. Substring before the separator >>> str1.partition('are')
2. Separator ('India is a Great Country',' ',' ')
3. Substring after the separator
If the separator is not found in the
string, it returns the whole string
itself and two empty strings
split() Returns a list of words delimited by >>> str1 = 'India is a Great
the specified substring. If no delimiter Country'
is given then words are separated by >>> str1.split()
space. ['India','is','a','Great','Country']
>>> str1 = 'India is a Great
Country'
>>> str1.split('a')
['Indi', ' is ', ' Gre', 't Country']
Programs in Strings
1. Program to count and display the number of
vowels,consonants,uppercase,lowercase characters in a string.

Str1=input("Enter a string=")
Vcount=Ccount=Lcount=Ucount=0
for i in Str1:
if i.isalpha():
if i.islower():
Lcount+=1
else:
Ucount+=1
if i in 'aeiouAEIOU':
Vcount+=1
else:
Ccount+=1

print("No. of vowels=",Vcount)
print("No. of consonants=",Ccount)
print("No. of Uppercase characters=",Ucount)
print("No. of Lowercase characters=",Lcount)

OUTPUT:
Enter a string=Python Program
No. of vowels= 3
No. of consonants= 10
No. of Uppercase characters= 2
No. of Lowercase characters= 11
2. Program to input a string and determine whether it is a palindrome or
not.
Str1=input("Enter a string=")
newstr=""
length=len(Str1)
for i in range(-1,-length-1,-1):
newstr+=Str1[i]
if Str1==newstr:
print("The given string is a palindrome")
else:
print("The given string is not a palindrome")
Output:
Enter a string=malayalam
The given string is a palindrome

3. Program to print a string in reverse order

Str1=input("Enter a string=")
newstr=""
length=len(Str1)
for i in range(-1,-length-1,-1):
newstr+=Str1[i]
print("The reversed string =",newstr)

Output:
Enter a string=python
The reversed string=nohtyp
4. Program to convert the case of characters in a string.

Str1=input("Enter a string=")
newstr=""
for ch in Str1:
if ch.islower():
newstr+=ch.upper()
elif ch.isupper():
newstr+=ch.lower()
else:
newstr+=ch
print("Changed string=",newstr)
OUTPUT:
Enter a string=PYTHON program 3.11
Changed string= python PROGRAM 3.11

5. Program to convert the case of characters (Title, alternate). (Program to


change the alternate characters in a given string and the first letter must
be upper case)

str1 = input("Enter a string=")


str2 = " "
length = len(str1)

str2 += str1[0].upper()
for i in range(1, length):
if i % 2 == 0:
if str1[i].islower():
str2 += str1[i].upper()
else:
str2 += str1[i].lower()
else:
str2 += str1[i]
print("The changed string =", str2)

6. Program to count the number of times a character occurs in a given string.

str1=input("Enter a string=")

ch1=input(“Enter the character to be counted=”)

count=0
for ch in str1:
if ch==ch1:
count+=1
print(“Number of times character“,ch1,”occurs in the string=”,count)

OUTPUT:
Enter a string=operator
Enter the character to be counted=o
Number of times character o occurs in the string= 2

7. Program to replace all the vowels in the string with *


str1=input("Enter a string=")
str2=" "
for ch in str1:
if ch in 'aeiouAEIOU':
str2+='*'
else:
str2+=ch
print("After replacing vowels with *=",str2)

OUTPUT:
Enter a string=python
After replacing vowels with *= pyth*n

********************

You might also like