python_string_list
python_string_list
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.
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
STR() FUNCTION
The str() function is used to convert the specified value into a string.
Syntax of str()
Here, encoding and errors parameters are only meant to be used when the object type is bytes
or byte array.
str() Parameters
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:
OPERATIONS ON STRING
String concatenation
# Defining strings
var1 = "Hello "
var2 = "World"
var1 = "Hello"
var2 = "World"
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
var1 = "Hello"
var2 = "World"
Output
Hello World
var1 = "Hello"
var2 = "World"
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!'
Output:
Hello World!
llo
llo World!
Example 2:
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.
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.
Syntax:
\Escape character
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
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.
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'
LIST
Lists are used to store multiple items in a single variable.
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.
A Python list is created using the square brackets, within which, the elements of a list are
defined.
Access Items
List items are indexed and you can access them by referring to the index number:
Negative Indexing
Negative indexing means start from the end.
-1 refers to the last item, -2 refers to the second last item etc.
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
OPERATIONS ON A LIST
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
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)
# descending order
sub_list.sort(reverse = True)
print(sub_list)
['Python', 'Perl', 'Java', 'C++']
Example:
sub_list = ['Python', 'Perl', 'Java', 'C++']
#remove Java
sub_list.remove('Java')
print(sub_list)
Example:
num_list = [1, 2, 3, 4]
num_list.pop()
print(num_list)
Output: [1, 2, 3]
Output: 4
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]
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.
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.
stack = []
stack.append('a')
stack.append('b')
stack.append('c')
print('Initial stack')
print(stack)
Output
Initial stack
['a', 'b', 'c']
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.
❖ 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
Output:
Initial queue
['a', 'b', 'c']
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.
When you want to insert an item at a specific position in a nested list, use insert()
method.
L[1]. insert(0,'xx')
print(L)
Output: ['a', ['xx', 'bb', 'cc'], 'd']
If you know the index of the item you want, you can use pop() method. It modifies the list and
returns the removed item.