Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
25 views

Lecture 7 - Strings in Python With Examples - 1

Nbbb

Uploaded by

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

Lecture 7 - Strings in Python With Examples - 1

Nbbb

Uploaded by

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

Strings in Python with Examples

In this article, I will discuss Strings in Python with Examples. Please read
our previous article discussing Looping Statements in Python with
examples. You will understand the following pointers in detail at the end
of this article.
1. What is a string in Python?
2. What is Slicing in Python?
3. What is Immutable in Python?
4. Strings are immutable in Python
5. Mathematical operators on string objects in Python
6. How do you find the length of a string in Python?
7. How to remove spaces from a string in Python?
8. How do you Find substrings in a string in Python?
9. How do you Count substrings in a given String in Python?
10. How to replace a string with another string in Python?
11. Does the replace() method modify the string objects
in Python?
12. How to Split a string in Python?
13. How to Join strings in Python?
14. How do you change cases of string in Python?
15. How to Formatting the Strings in Python?
Reminder
We have already learned the first Hello World program in Python. In that
program, we print a group of characters using the print() function. Those
groups of characters are called a string.

Program to print string (Demo1.py)


print(“Welcome to Python programming”)
Output: Welcome to Python programming

What is a string in Python?


A string is a group of characters enclosed within single, double, or triple
quotes. We can say the string is a sequential collection of characters.
Program to print employee information (Demo2.py)
name = "Balayya"
emp_id = 20
print("Name of the employee: ", name)
print("employee id is :", emp_id)
Output:

Note: Generally, to create a string, the most used syntax is double


quotes syntax.

When are single and triple-double quotes are used?


If you want to create multiple lines of string, then triple-single or triple-
double quotes are the best to use.
Program to print multi-line employee information (Demo3.py)
loc1 = """XYZ company
While Field
Bangalore"""
loc2 = """XYZ company
Banglore
Human tech park"""
print(loc1)
print(loc2)
Output:

Note: Inside string, we can use single and double quotes

Program to use single and double quotes inside a string (Demo4.py)


s1 = "Welcome to 'python' learning"

for embedding single quote text in a string the string must be in double
quote
s2 = 'Welcome to "python" learning'
for embedding double quote text in a string the string must be in single
quote

s3 = """Welcome to 'python' learning is "very" simple """


print(s1)
print(s2)
print(s3)
Output:

Welcome to 'python' learning is "very" simple

The Empty string in Python:


If a string has no characters, it is called an empty string.
Program to print an empty string (Demo5.py)
s1 = ""
print(s1)
Output:
Accessing string characters in Python:
We can access string characters in Python by using,
• Indexing
• Slicing
Indexing:
Indexing means the position of the string’s characters where it is stored.
We need to use square brackets [] to access the string index.
The string indexing result is string type.
String indices should be integers; otherwise, we will get an error. We
can access the index within the index range; otherwise, we will get an
error.
# 0123456789012
s1 = "pauri garhwal"

for i in range(len(s1)):
print(i,' element is = ',s1[i],' id = ', id(s1[i]))
Output
0 element is = p id = 140731012446792
1 element is = a id = 140731012445952
2 element is = u id = 140731012447072
3 element is = r id = 140731012446904
4 element is = i id = 140731012446400
5 element is = id = 140731012442312
6 element is = g id = 140731012446288
7 element is = a id = 140731012445952
8 element is = r id = 140731012446904
9 element is = h id = 140731012446344
10 element is = w id = 140731012447184
11 element is = a id = 140731012445952
12 element is = l id = 140731012446568

Python supports two types of indexing.


1. Positive indexing: The position of string characters can be a
positive index from left to right direction (we can say forward
direction). In this way, the starting position is 0 (zero).

2. Negative indexing: The position of string characters can be


negative indexes from right to left direction (we can say
backward direction). In this way, the starting position is -1
(minus one).
Diagram representation

Note: If we try to access characters of a string without a range index, we


will get an error as IndexError.

Example: Accessing a string with an index in Python (Demo6.py)


wish = "Hello World"
print(wish[0])
print(wish[1])
Output:

# 01234567890
s1 = 'Ashish Negi'

print(s1[1])
for i in range(len(s1)):
print(s1[i], end = " ")
print()
for i in range(len(s1)):
print(i, end = " ")
Output :
Ashish Negi
0 1 2 3 4 5 6 7 8 9 10

# 0123456789012
s1 = "pauri garhwal"
# 3210987654321 negative index

for i in range(len(s1)):
print(i,' element is = ',s1[i],' id = ', id(s1[i]))
for i in range(-1,(-1)*(len(s1)+1),-1 ):
print(i,' element is = ',s1[i])

Output :

0 element is = p id = 140731012446792

1 element is = a id = 140731012445952

2 element is = u id = 140731012447072

3 element is = r id = 140731012446904

4 element is = i id = 140731012446400

5 element is = id = 140731012442312

6 element is = g id = 140731012446288

7 element is = a id = 140731012445952

8 element is = r id = 140731012446904

9 element is = h id = 140731012446344

10 element is = w id = 140731012447184

11 element is = a id = 140731012445952

12 element is = l id = 140731012446568

-1 element is = l

-2 element is = a

-3 element is = w
-4 element is = h

-5 element is = r

-6 element is = a

-7 element is = g

-8 element is =

-9 element is = i

-10 element is = r

-11 element is = u

-12 element is = a

-13 element is = p

Example: Accessing a string with float index in Python (Demo7.py)


wish = "Hello World"
print(wish[1.3])
Output:

Example: Accessing a string without a bound index (Demo8.py)


wish = "Hello World"
print(wish[100])
Output:
IndexError: string index out of range
Example: Accessing a string with a negative index (Demo9.py)
wish = "Hello World"
print(wish[-1])
print(wish[-2])
Output:
# 01234567890
s1 = 'Ashish Negi'
# 09876543210 (negative)

#Forward traversing of a string


print(s1[1])
for i in range(len(s1)):
print(s1[i], end = " ")
print()
for i in range(len(s1)):
print(i, end = " ")

for i in range (-1,(-1)*(len(s1)+1),-1):


print(s1[i], end = " ")
print()
for i in range(len(s1)):
print(i, end = " ")

Example: Printing character by character using for loop (Demo10.py)


name ="Python"
for a in name:
print(a)
Output:

What is Slicing in Python?


A substring of a string is called a slice. A slice can represent a part of a
string from a string or a piece of string.
The string slicing result is string type. We need to use square brackets []
in slicing. In slicing, we will not get any index out-of-range exceptions. In
slicing, indices should be integer or None or __index__ method
otherwise, we will get errors.
Syntax:

Example:

Different Cases:
wish = “Hello World”
1. wish [::] => accessing from 0th to last
2. wish [:] => accessing from 0th to last
3. wish [0:9:1] => accessing string from 0th to 8th means (9-1)
element.
4. wish [0:9:2] => accessing string from 0th to 8th means (9-1)
element.
5. wish [2:4:1] => accessing from 2nd to 3rd characters.
6. wish [:: 2] => accessing entire in steps of 2
7. wish [2 ::] => accessing from str[2] to ending
8. wish [:4:] => accessing from 0th to 3 in steps of 1
9. wish [-4: -1] => access -4 to -1

Note:
• If you are not specifying the beginning index, it will consider
the beginning of the string.
• If you are not specifying the end index, it will consider the
end of the string.
• The default value for the step is 1
Example: Slicing operator using several use cases (Demo11.py)
wish = "Hello World"
print(wish[::])
print(wish[:])
print(wish[0:9:1])
print(wish[0:9:2])
print(wish[2:4:1])
print(wish[::2])
print(wish[2::])
print(wish[:4:])

print(wish[-4:-1])
Output:

What is Immutable in Python?


Once we create an object, then the state of the existing object cannot
be changed or modified.
This behavior is called immutability.

Once we create an object, then the state of the existing object can be
changed or modified. This behavior is called mutability.

Strings are immutable in Python:


A string having an immutable nature. Once we create a string object, we
cannot change or modify the existing object.

Example: Immutable (Demo12.py)


name = "Balayya"

You might also like