0% found this document useful (0 votes)
11 views19 pages

python_string_list

Uploaded by

deepakgowdamc
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
11 views19 pages

python_string_list

Uploaded by

deepakgowdamc
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 19

1|Page

STRING
A string is a group or a sequence of characters. Which is placed inside a pair of single
or double quotes.
strings are immutable, which means we can ‘t change an existing string.

ACCESSING CHARACTERS IN STRING


In Python, individual characters of a String can be accessed by using the method of
Indexing.
Once you define a string, python allocate an index value for its each character.
These index values are otherwise called as subscript which are used to access and
manipulate the strings.
The index can be positive or negative integer numbers.
The positive index 0 is assigned to the first character and n-1 to the last character, where
n is the number of characters in the string.
The negative index assigned from the last character to the first character in reverse
order begins with -1.

Example 1 : Program to access each character with its positive subscript of a giving
string
str1 = input ("Enter a string: ")
index=0
for i in str1:
print ("Subscript[",index,"] : ", i)
index + = 1

Output

Python programming Bhavani M


2|Page

Enter a string: welcome


Subscript [ 0 ] : w
Subscript [ 1 ] : e
Subscript [ 2 ] : l
Subscript [ 3 ] : c
Subscript [ 4 ] : o
Subscript [ 5 ] : m
Subscript [ 6 ] : e

STR() FUNCTION
The str() function is used to convert the specified value into a string.

Syntax of str()

str(object, encoding='utf-8', errors='strict')

Here, encoding and errors parameters are only meant to be used when the object type is bytes
or byte array.

str() Parameters

The str() method takes three parameters:


• object - whose string representation is to be returned
• encoding - that the given byte object needs to be decoded to (can be UTF-8, ASCII, etc)
• errors - a response when decoding fails (can be strict, ignore, replace, etc)

Example of str() in Python

Let us convert a number into a string object using the method, str in python.

number = 55
string = str(number)
print("Converted string is:",string)

Output:

The converted string is: 55

Python programming Bhavani M


3|Page

OPERATIONS ON STRING

String concatenation

String Concatenation is a very common operation in programming. String Concatenation is


the technique of combining two strings.
Python String Concatenation can be done using various ways.

• String Concatenation using + Operator


It‘s very easy to use the + operator for string concatenation.
This operator can be used to add multiple strings together.
The arguments must be a string. Here, The + Operator combines the string that is stored
in the var1 and var2 and stores in another variable var3.

Note: Strings are immutable, therefore, whenever it is concatenated, it is assigned to a new


variable.

# Defining strings
var1 = "Hello "
var2 = "World"

# + Operator is used to combine strings


var3 = var1 + var2
print(var3)

Output: Hello World

• String Concatenation using join() Method


The join() method is a string method and returns a string in which the elements of the
sequence have been joined by str separator.
This method combines the string that is stored in the var1 and var2.
It accepts only the list as its argument and list size can be anything.

var1 = "Hello"
var2 = "World"

# join() method is used to combine the strings


print("".join([var1, var2]))

Output
Python programming Bhavani M
4|Page

HelloWorld
String Concatenation using % Operator
We can use the % operator for string formatting, it can also be used for string
concatenation.
It’s useful when we want to concatenate strings and perform simple formatting.
The %s denotes string data type. The value in both the variable is passed to the string
%s and becomes ―Hello World‖.

var1 = "Hello"
var2 = "World"
# % Operator is used here to combine the string
print ("% s % s" % (var1, var2))
Output
Hello World

• String Concatenation using format () function


string format () is one of the string formatting methods in Python, which allows multiple
substitutions and value formatting.
The curly braces {} are used to set the position of strings.
The first variable stores in the first curly braces and the second variable stores in the
second curly braces. Finally, it prints the value Hello World.

var1 = "Hello"
var2 = "World"

# format function is used here to


# combine the string
print("{} {}".format(var1, var2))

Output
Hello World

• String Concatenation using (, comma)


, is a great alternative to string concatenation using +.
when you want to include single whitespace. Use a comma when you want to combine
data types with single whitespace in between.

var1 = "Hello"
var2 = "World"

Python programming Bhavani M


5|Page

# , to combine data types with a single whitespace.


print(var1, var2)

Output
Hello World

STRING SLICING
A segment of a string is called a slice.
Subsets of strings can be taken using the slice operator ([ ] and [:]) with indexes starting
at 0 in the beginning of the string and working their way from -1 at the end.
Syntax [Start: stop: steps]

• Slicing will start from index and will go up to stop in step of steps.
• Default value of start is 0
• Stop is last index of list
• And for step default is 1

Example 1:
str = 'Hello World!'

print str # Prints complete string

print str[0] # Prints first character of the string

print str[2:5] # Prints characters starting from 3rd to 5th

print str[2:] # Prints string starting from 3rd character print

Output:
Hello World!

llo
llo World!

Example 2:

Python programming Bhavani M


6|Page

x='computer'
▪ x[1:4] output: 'omp'
▪ x[:5] output 'compu'
▪ x[:-2] output 'comput'

TRAVERSING A STRING

• Traversing just means to process every character in a string, usually from left end to right
end
• One way to write a traversal is with a while loop:
fruit = "fruit"
index = 0
while index < len(fruit):
letter = fruit[index]
print(letter)
index = index + 1

This loop traverses the string and displays each letter on a line by itself.

Python programming Bhavani M


7|Page

ESCAPE SEQUENCE

Escape characters or sequences are illegal characters for Python and never get printed as
part of the output.
When backslash is used in Python programming, it allows the program to escape the
next characters.
Escape sequences allow you to include special characters in strings. To do this, simply
add a backslash (\) before the character you want to escape.

Following would be the syntax for an escape sequence

Syntax:

\Escape character

Python programming Bhavani M


8|Page

RAW STRING

A raw string can be used by prefixing the string with r or R, which allows for backslashes to
be included without the need to escape them.
Example:
print(r"Backslashes \ don't need to be escaped in raw strings.")

Output:
Backslashes \ don't need to be escaped in raw strings.
But keep in mind that unescaped backslashes at the end of a raw string will cause an error

print(r"There's an unescaped backslash at the end of this string\")

Output:
File "main.py", line 1
print(r"There's an unescaped backslash at the end of this string\")
SyntaxError: EOL while scanning string literal

UNICODE STRING

Normal strings in Python are stored internally as 8-bit ASCII, while Unicode strings are stored
as 16-bit Unicode. This allows for a more varied set of characters, including special characters
from most languages in the world.

Example
#!/usr/bin/python
print u'Hello, world!'
Output
When the above code is executed, it produces the following result −
Hello, world!

STRING METHODS

split()
split() method splits the string according to delimiter str (space if not provided)
Example:
string="Nikhil Is Learning"
Python programming Bhavani M
9|Page

string.split()

['Nikhil', 'Is', 'Learning']

count()
count() method counts the occurrence of a string in another string
Example:
string='Nikhil Is Learning'
string.count('i')
3

find()
find() method is used for finding the index of the first occurrence of a string in another
string.
Example:
string="Nikhil Is Learning"
string.find('k')
2
swapcase()
converts lowercase letters in a string to uppercase and viceversa
Example:
string="HELLO"
string.swapcase()
'hello'

startswith()
Determines if string or a substring of string starts with that particular character.returns true if so
and false otherwise.
Example:
string="Nikhil Is Learning"
string.startswith('N')
True

endswith()
Determines if string or a substring of string ends with that particular character it returns true if
so and false otherwise.

Python programming Bhavani M


10 | P a g e

Example:
string="Nikhil Is Learning"

string.endswith('g')

True

Lower()
Convert the string with all the upper case letter to lower case.
Example:
String="HELLO"
String.lower()
Output:
hello
Upper()
Convert the string with all the lower case letter to upper case.
Example:
String="hello"
String.upper()
Output:
HELLO
replace()
replace() method replaces occurrences of old string with new string
Example:
string="Nikhil Is Learning"
string.replace('Nikhil','Neha')
'Neha Is Learning'

Python programming Bhavani M


11 | P a g e

LIST
Lists are used to store multiple items in a single variable.

List items are ordered, changeable, and allow duplicate values.

To use a list, you must declare it first. Do this using square brackets and separate values
with commas.

List items are indexed, the first item has index [0], the second item has index [1] etc.

A list need not be homogeneous; that is, the elements of a list do not all have
to be of the same type.
Example:
list1=[1,2,3,'A','B',7,8, [10,11]]
print(list1)
[1, 2, 3, 'A', 'B', 7, 8, [10, 11]]

Properties of Lists

Python Lists are ordered and mutable (or changeable). Let’s understand this further:

Ordered: There is a defined order of elements within a list. New elements are added to the
end of the list.

Mutable: We can modify the list i.e add, remove and change elements of a python list.

Creating python list

A Python list is created using the square brackets, within which, the elements of a list are
defined.

Python programming Bhavani M


12 | P a g e

The elements of a list are separated by commas.


Creating a list
a = [1, 2, 3, 4, 5]
Avengers = ['hulk', 'iron-man', 'Captain', 'Thor']

Access Items
List items are indexed and you can access them by referring to the index number:

Example: Second item of the list:

List = ["apple", "banana", "cherry"]


print(List[0]) output: apple
print(List[1]) output: banana
print(List[2]) output: cherry

Negative Indexing
Negative indexing means start from the end.
-1 refers to the last item, -2 refers to the second last item etc.

Example: Print the last item of the list:

thislist = ["apple", "banana", "cherry"]


print(thislist[-1])

Range of Indexes
You can specify a range of indexes by specifying where to start and where to end the range.
When specifying a range, the return value will be a new list with the specified items.

Example

list = ["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"]


print(list[2:5])
cherry,orange,kiwi

OPERATIONS ON A LIST

Access elements of a list


We can access the elements of a python list using the index value. The index starts at 0
Python programming Bhavani M
13 | P a g e

To access consecutive elements of a list, we can use colon(:) and set the range of indexes like this
[1:5]. The last index within the range is not considered in the output, so [1:5] will give elements
from indexes 1 to 4. We can use the negative index to access elements from the last. Index -1 will
give the last element, index-2 will give 2nd last element, etc.

Example:
mix_list = [1, 'Jerry', 'Science', 79.5, True]
print(mix_list[0])
output: 1
print(mix_list[3])
output: 79.5

Adding (or Appending) element


Elements can be added (or appended) to the python lists using the append and insert function.
Using the insert function, we can add elements at any position of a list.
The function takes 2 arguments:
1) Index at which we want to insert the element.The element that we want to insert.
2)The append function is used to add elements to the end of a list.

Example:
sub_list = ['Python', 'Perl', 'Java', 'C++']
sub_list.insert(3,'R')
print(sub_list)
output: ['Python', 'Perl', 'Java', 'R', 'C++']

# Using append
sub_list.append('Django')
print(sub_list)
output: ['Python', 'Perl', 'Java', 'R', 'C++', 'Django']

Sorting Lists
We can sort the elements of the list in ascending or descending order. In the below code, we are
sorting the subject list in ascending and descending order (using reverse = True).
Example:
sub_list = ['Python', 'Perl', 'Java', 'C++']
# ascending order
sub_list.sort()
print(sub_list)

Python programming Bhavani M


14 | P a g e

['C++', 'Java', 'Perl', 'Python']

# descending order
sub_list.sort(reverse = True)
print(sub_list)
['Python', 'Perl', 'Java', 'C++']

Update elements of a list


Because lists are changeable, we can update the elements of the lists using the index of the
elements. For example, in the code below we are updating Science to Computer using the index
of Science.
Example:
mix_list = [1, 'Jerry', 'Science', 79.5, True]
mix_list[2] = 'Computer'
print(mix_list)

Output: [1, 'Jerry', 'Computer', 79.5, True]

Delete elements of a list


We can easily delete the element of a list using remove function.Suppose, we want to delete Java
from our subject list, then we can delete it using the remove function and provide Java as an
argument.

Example:
sub_list = ['Python', 'Perl', 'Java', 'C++']

#remove Java
sub_list.remove('Java')
print(sub_list)

Output: ['Python', 'Perl', 'C++']

Pop the elements of a list


The pop function is used to remove or pop out the last element from the list and output the
remaining elements.

Example:
num_list = [1, 2, 3, 4]

Python programming Bhavani M


15 | P a g e

num_list.pop()
print(num_list)

Output: [1, 2, 3]

Length/Number of elements in a list


We can find the total number of elements in a list using the length function.
Example
num_list = [1, 3, 4, 5]
#length of a list
print(len(num_list))

Output: 4

Maximum element within a list


We can easily find the maximum of the numbers which are present within a list using the very
intuitive max function.Max function only work on homogenous list i.e. lists having elements of the
same data type.

Example
num_list = [1, 3, 4, 5]
max(num_list)

Output: 5

Concatenate lists
We can easily concatenate 2 lists using the + operator. (Concatenation is like appending 2 lists).

num_list1 = [1, 3, 4, 5]
num_list2 = [5, 6, 7]
print(num_list1 + num_list2)

Output: [1, 3, 4, 5, 5, 6, 7]

IMPLEMENTATION OF STACK AND QUEUE USING LIST

STACK IN PYTHON
A stack is a linear data structure that stores items in a Last-In/First-Out (LIFO) or First-
In/Last-Out (FILO) manner.

Python programming Bhavani M


16 | P a g e

In stack, a new element is added at one end and an element is removed from that end
only.
The insert and delete operations are often called push and pop.

The functions associated with stack are:

❖ empty() – Returns whether the stack is empty


❖ size() – Returns the size of the stack
❖ peek() – Returns a reference to the topmost element of the stack
❖ push() – Inserts the element at the top of the stack
❖ pop() – Deletes the topmost element of the stack

Python program to demonstrate stack implementation

stack = []

stack.append('a')
stack.append('b')
stack.append('c')

print('Initial stack')
print(stack)

print('\nElements popped from stack:')


print(stack.pop())
print(stack.pop())
print(stack.pop())

print('\nStack after elements are popped:')


print(stack)

Output
Initial stack
['a', 'b', 'c']

Elements popped from stack:


c
b
Python programming Bhavani M
17 | P a g e

Stack after elements are popped:


[]

QUEUE IN PYTHON
queue is a linear data structure that stores items in First In First Out (FIFO) manner.
With a queue the least recently added item is removed first.
A good example of queue is any queue of consumers for a resource where the consumer that
came first is served first.

Operations associated with queue are:

❖ Enqueue: Adds an item to the queue. If the queue is full, then it is said to be an Overflow
condition.
❖ Dequeue: Removes an item from the queue. The items are popped in the same order in
which they are pushed. If the queue is empty, then it is said to be an Underflow condition
❖ Front: Get the front item from queue
❖ Rear: Get the last item from queue

Python program to demonstrate queue implementation using list


queue = []
queue.append('a')
queue.append('b')
queue.append('c')
print("Initial queue")
print(queue)
print("\nElements dequeued from queue")
print(queue.pop(0))
print(queue.pop(0))
print(queue.pop(0))
print("\nQueue after removingelements")
print(queue)

Output:

Python programming Bhavani M


18 | P a g e

Initial queue
['a', 'b', 'c']

Elements dequeued from queue


a
b
c

Queue after removing elements


[]

NESTED LIST
A list within another list is referred to as a nested list in Python.
We can also say that a list that has other lists as its elements is a nested list.
Here is an illustration of a Python nested list:
MyList = [[22, 14, 16], ["Joe", "Sam", "Abel"], [True, False, True]]
To access the elements in this nested list we use indexing.
To access an element in one of the sublists, we use two indices – the index of the sublist and
the index of the element within the sublist.

Example of the nested list:


MyList = [[22, 14, 16], ["Joe", "Sam", "Abel"], [True, False, True]]
print(MyList[0])
[22, 14, 16]
print(MyList[0][1])
output: 14

❖ Add items to a Nested list


To add new values to the end of the nested list, use append() method.

L = [['a', 'b', 'c'],[‘bb', 'cc']]


L[1].append('xx')
print(L)
Output: [['a', 'b', 'c'], ['bb', 'cc', 'xx']]

When you want to insert an item at a specific position in a nested list, use insert()
method.

L = ['a', ['bb', 'cc'], 'd']

Python programming Bhavani M


19 | P a g e

L[1]. insert(0,'xx')
print(L)
Output: ['a', ['xx', 'bb', 'cc'], 'd']

❖ Remove items from a Nested List

If you know the index of the item you want, you can use pop() method. It modifies the list and
returns the removed item.

L = ['a', ['bb', 'cc', 'dd'], 'e']


L[1].pop(1)
print(L)
Output: ['a', ['bb', 'dd'], 'e']

❖ Find Nested List Length


You can use the built-in len() function to find how many items a nested sublist has.
L = ['a', ['bb', 'cc'], 'd']
print(len(L))
Output: 3
print(len(L[1]))
Output : 2

Python programming Bhavani M

You might also like