0% found this document useful (0 votes)
2 views

Chapter 8 Strings print

The document provides an introduction to strings in Python, explaining their creation, immutability, and various operations such as concatenation, repetition, membership, and slicing. It also covers string traversal using loops and lists several built-in string methods and functions. Additionally, it includes examples of handling strings, such as counting character occurrences and manipulating string content.

Uploaded by

Saraswathi
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

Chapter 8 Strings print

The document provides an introduction to strings in Python, explaining their creation, immutability, and various operations such as concatenation, repetition, membership, and slicing. It also covers string traversal using loops and lists several built-in string methods and functions. Additionally, it includes examples of handling strings, such as counting character occurrences and manipulating string content.

Uploaded by

Saraswathi
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 7

» Introduction to Strings

» String Operations
» Traversing a String
» Strings Method and Built-in Functions
» Handling Strings

1.STRINGS
String is a sequence which is made up of one or more UNICODE characters.
A string can be created by enclosing one or more characters in single, double or
triple quote.
>>> str1 = 'Hello World!'
>>> str2 = "Hello World!"
>>> str3 = """Hello World!"""
>>> str4 = '''Hello World!''

str1, str2, str3, str4 are all string variables having the same value 'Hello World!'.

2. Accessing Characters in a String


Each individual character in a string can be accessed using a technique called
indexing.
The index specifies the character to be accessed in the string and is written in
square brackets ([ ]).
The index of the first character (from left) in the string is 0 and the last character is
n-1 where n is the length of the string.
#initializes a string str1
>>> str1 = 'Hello World!'
#gives the first character of str1
>>> str1[0]
'H'
#gives seventh character of str1
>>> str1[6]
'W'
#gives last character of str1
>>> str1[11]
'!'
#gives error as index is out of range
>>> str1[15]
IndexError: string index out of range
Indexing of characters in string 'Hello World!'
An inbuilt function len() in Python returns the length of the string that is passed as
parameter. For example, the length of string str1 = 'Hello World!' is 12.
#gives the length of the string str1
>>> len(str1)
12
#length of the string is assigned to n
>>> n = len(str1)
>>> print(n)
12
#gives the last character of the string
>>> str1[n-1]
'!'
#gives the first character of the string
>>> str1[-n]
'H'

String is Immutable
A string is an immutable data type. It means that the contents of the string
cannot be changed after it has been created.
>>> str1 = "Hello World!" #if we try to replace character 'e' with 'a'
>>> str1[1] = 'a'
TypeError: 'str' object does not support item assignment

3. STRING OPERATIONS
 String is a sequence of characters.
 Python allows certain operations on string data type, such as
concatenation, repetition, membership and slicing.
Concatenation
 To concatenate means to join.
 Python allows us to join two strings using concatenation operator plus
which is denoted by symbol +
>>> str1 = 'Hello' #First string
>>> str2 = 'World!' #Second string
>>> str1 + str2 #Concatenated strings
'HelloWorld!'
#str1 and str2 remain same
#after this operation.
>>> str1
'Hello'
>>> str2
'World!'
Repetition
 Python allows us to repeat the given string using repetition operator
which is denoted by symbol *.
#assign string 'Hello' to str1
>>> str1 = 'Hello'
#repeat the value of str1 2 times
>>> str1 * 2
'HelloHello'
#repeat the value of str1 5 times
>>> str1 * 5
'HelloHelloHelloHelloHello'

Membership:
 Python has two membership operators 'in' and 'not in'.
 The 'in' operator takes two strings and returns True if the first string
appears as a substring in the second string, otherwise it returns False.
>>> str1 = 'Hello World!'
>>> 'W' in str1
True
>>> 'Wor' in str1
True
>>> 'My' in str1
False
 The 'not in' operator also takes two strings and returns True if the first
string does not appear as a substring in the second string, otherwise
returns False.
>>> str1 = 'Hello World!'
>>> 'W' in str1
True
>>> 'Wor' in str1
True
>>> 'My' in str1
False

Slicing
 In Python, to access some part of a string or substring, we use a
method called slicing.
 This can be done by specifying an index range.
 We can say that str1[n:m] returns all the characters starting from
str1[n] till str1[m-1].
>>> str1 = 'Hello World!'
#gives substring starting from index 1 to 4
>>> str1[1:5]
'ello'
#gives substring starting from 7 to 9
>>> str1[7:10]
'orl'
#index that is too big is truncated down to
#the end of the string
>>> str1[3:20]
'lo World!'
#first index > second index results in an
#empty '' string
>>> str1[7:2]

4. 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
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.

5. STRING METHODS AND BUILT-IN FUNCTIONS:


Python has several built-in functions that allow us to work with
strings

len() : Returns length of the given string . Ex: len(str1)


title() : Returns string with sentence case. Ex: str1.title()
lower() : Returns strings to lower case. Ex: str1.lower()
upper(): Returns strings to lower case. Ex: str1.upper()
isalnum() : Returns True if characters of the given string are either alphabets or
numeric. Ex: str1. isalnum ()
islower():Returns True if the string is non-empty and has all lowercase
alphabets. Ex: str1. islower ()
isupper():Returns True if the string is non-empty and has all lowercase
alphabets. Ex: str1. isupper ()
isspace() : Returns True if the string is non-empty and all characters
are white spaces
istittle() :
lstrip() : Returns the string after removing the spaces only on the left of the string
rstrip() : Returns the string after removing the spaces only on the left of the string
strip() :
join() : Returns a string in which the characters in the string have been joined by a
separator
replace(ostr,nstr) : Replaces all occurrences of old string with the new string
partition() : Partitions the given string at the first occurrence of the substring
split():Returns a list of words delimited by the specified substring
startswith() : Returns True if the given string starts with the string
endswith():Returns True if the given string ends with the
6. HANDLING STRINGS: To perform different operations on strings.
#Function to count the number of times a character occurs in a string
def charCount(ch,st):
count = 0
for character in st:
if character == ch:
count += 1
return count
#end of function
st = input("Enter a string: ")
ch = input("Enter the character to be searched: ")
count = charCount(ch,st)
print("Number of times character",ch,"occurs in the string is:",count)
# string as a parameter which replaces all vowels in the string with '*'

#print it in the reverse order without creating a new string

# to check if a string is a palindrome or not.

You might also like