Python_Unit2_Part1
Python_Unit2_Part1
Unit - 2
STRINGS
A string is a data structure in Python that represents a sequence of
characters. It is an immutable data type, meaning that once you have created a
string, you cannot change it. Strings are used for storing and manipulating text
data, representing names, addresses, and other types of data that can be
represented as text.
Example:
Python does not have a character data type, a single character is simply
a string with a length of 1.
Square brackets can be used to access elements of the string.
Strings in Python can be created using single quotes or double quotes or even
triple quotes.
Example:
string1=‟Sapient‟
string2=”Sapient”
string3=‟‟‟Sapient‟‟‟
Only Integers are allowed to be passed as an index, float or other types that will
cause a TypeError.
# characters of String
String1 = "GeeksForGeeks"
print(String1)
print(String1[0])
print(String1[-1])
Output:
Initial String:
GeeksForGeeks
The str() function is used to convert the specified value into a string.
Syntax:
str(object='')
str(object=b'', encoding='utf-8', errors='strict')
Parameter:
Name Description
Return value:
A string.
print(str(15))
Output:
15
Example: Python str() function
# str()
print(s)
Output:
String
Operations on Strings
1. Concatenation
x = "Python is "
y = "awesome"
z= x+y
print(z)
a = "Hello"
b = "World"
c=a+""+b
print(c)
2. Comparison
The relational operators compare the Unicode values of the characters of the
strings from the zeroth index till the end of the string. It then returns a boolean
value according to the operator used.
print("Geek" == "Geek")
print("Geek" != "Geek")
output- TRUE
TRUE
FALSE
FALSE
“Geek” == “Geek” will return True as the Unicode of all the characters are equal
In case of “Geek” and “geek” as the unicode of G is \u0047 and of g is \u0067
“Geek” < “geek” will return True and “Geek” > “geek” will return False
The == operator compares the values of both the operands and checks for value
equality. Whereas is operator checks whether both the operands refer to the
same object or not. The same is the case for != and is not.
3. Slicing
String slicing in Python is about obtaining a sub-string from the given string by
slicing it respectively from start to end.
The slice() constructor creates a slice object representing the set of indices
specified by range(start, stop, step).
Syntax:
slice(stop)
slice(start, stop, step)
Parameters: start: Starting index where the slicing of object starts.
stop: Ending index where the slicing of object stops.
step: It is an optional argument that determines the increment between each
index for slicing.
Return Type:: Returns a sliced object containing elements in the given range
only.
String = 'ASTRING'
s1 = slice(3)
s2 = slice(1, 5, 2)
print("String slicing")
print(String[s1])
print(String[s2])
print(String[s3])
Output:
String slicing
AST
SR
GITA
In Python, indexing syntax can be used as a substitute for the slice object. A
start, end, and step have the same mechanism as the slice() constructor.
Syntax
4. Joining
Example:
str = '-'.join('hello')
print(str)
Output:
h-e-l-l-o
Syntax: string_name.join(iterable)
Parameters:
Return Value: The join() method returns a string concatenated with the
elements of iterable.
Type Error: If the iterable contains any non-string values, it raises a TypeError
exception.
print("".join(list1))
print("$".join(list1))
Output:
geeks
$g$e$e$k$s$
5. Traversing
string_name = "geeksforgeeks"
print("\n")
string_name = "GEEKS"
print(string_name[element])
Output:
geeksforgeeks
string_name = "Geeks"
for i, v in enumerate(string_name):
print(v)
Output:
string_name = "GEEKS"
print('\n')
Output:
SKEEG
Format Specifiers
String formatting
Output:
The mangy, scrawny stray dog hurriedly gobbled down the grain-free, organic
dog food.
‘%s’ is used to inject strings similarly ‘%d’ for integers, ‘%f’ for floating-point
values, ‘%b’ for binary forma
Output:
Python3
'the', 'Read'))
Output:
To create an f-string, prefix the string with the letter “ f ”. The string itself can
be formatted in much the same way that you would with str.format()
name = 'Ele'
Output:
My name is Ele.
In the String module, Template Class allows us to create simplified syntax for
output specification. The format uses placeholder names formed by $ with valid
Python identifiers (alphanumeric characters and underscores). Surrounding
the placeholder with braces allows it to be followed by more alphanumeric
letters with no intervening spaces. Writing $$ creates a single escaped $:
# string interpolation
n1 = 'Hello'
n2 = 'GeeksforGeeks'
# template string.
print(n.substitute(n3=n1, n4=n2))
Output:
The center() method is a built-in method in Python‟s str class that returns a
new string that is centered within a string of a specified width.
string = "GeeksForGeeks!"
width = 30
centered_string = string.center(width)
print(centered_string)
Output
GeeksForGeeks!
Escape Sequences
Let's suppose we need to write the text as - They said, "Hello what's going on?"-
the given statement can be written in single quotes or double quotes but it will
raise the SyntaxError as it contains both single and double-quotes.
Example
Consider the following example to understand the real use of Python operators.
Output:
2. \\ Backslash print("\\")
Output:
\
Hello World!
In Python, when you prefix a string with the letter r or R such as r'...' and R'...',
that string becomes a raw string. Unlike a regular string, a raw string treats
the backslashes (\) as literal characters.
Raw strings are useful when you deal with strings that have many
backslashes, for example, regular expressions or directory paths on Windows.
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.
#!/usr/bin/python
Function
Name Description
Function
Name Description
rindex() Returns the highest index of the substring inside the string
rsplit() Split the string from the right by the specified separator
Function
Name Description
strip() Returns the string with both leading and trailing characters
LISTS
Creating List
The list is a sequence data type which is used to store the collection ofdata. A
single list may contain DataTypes like Integers, Strings, as well as Objects.
Lists are mutable, and hence, they can be altered even after their creation.
Lists in Python can be created by just placing the sequence inside the square
brackets[]. Unlike Sets, a list doesn‟t need a built-in function for its creation of
a list.
# Creating a List
List = []
print(List)
print(List)
# using index
print(List[0])
print(List[2])
Output
Blank List:
[]
List of numbers:
List Items:
Geeks
Geeks
Operations on List
stack.append("Ram")
stack.append("Iqbal")
print(stack)
print(stack.pop())
print(stack)
print(stack.pop())
print(stack)
Output:
Iqbal
Ram
queue.append("Ram")
queue.append("Iqbal")
print(queue)
print(queue.pop(0))
print(queue)
Output:
Amar
Nested Lists
A list within another list is referred to as a nested list in Python.
MyList = [[22, 14, 16], ["Joe", "Sam", "Abel"], [True, False, True]]
#printing a sublist
print(MyList[0])
#output [22, 14, 16]
print(MyList) #output:[[22, 20, 16], ["Joe", "Sam", "Abel"], [True, False, True]]
Dictionaries
Dictionary in Python is a collection of keys values, used to store data values
like a map, which, unlike other data types which hold only a single value as an
element.
Creating Dictionaries
A dictionary can be created by placing a sequence of elements within
curly {} braces, separated by „comma‟. Dictionary holds pairs of values, one
being the Key and the other corresponding pair element being its Key:value.
Values in a dictionary can be of any data type and can be duplicated, whereas
keys can‟t be repeated and must be immutable.
Note – Dictionary keys are case sensitive, the same name but different cases of
Key will be treated distinctly.
country_capitals = {
"United States": "Washington D.C.",
"Italy": "Rome",
"England": "London"
}
Operation on Dictionaries
1. Definition operations
1.1.{ }
y = {}
2. Mutable operations
2.1. [ ]
Adds a new pair of key and value to the dictionary, but in case that the key
already exists in the dictionary, we can update the value.
y = {}
y['one'] = 1
y['two'] = 2
print(y)
Output:{'one': 1, 'two': 2}
2.2. del
2.3. update
This method updates a first dictionary with all the key-value pairs of a second
dictionary. Keys that are common to both dictionaries, the values from the
second dictionary override those of the first.
x = {'one': 0, 'two': 2}
y = {'one': 1, 'three': 3}
x.update(y)print(x)
3. Immutable operations
3.1. len
x = {'one': 0, 'two': 2}
print(len(x))
Output:2
3.2. keys
This method allows you to get all the keys in the dictionary. It is often used in a
“for loop” to iterate over the content of a dictionary.
x = {'one': 1, 'two': 2}
print(x.keys())
Output:dict_keys(['one', 'two'])
3.3. values
This method allows you to obtain all the values stored in a dictionary.
rint(x.values())
Output:dict_values([1, 2])
3.4. items
Returns all the keys and their associated values as a sequence of tuples.
x = {'one': 1, 'two': 2}
print(x.items())
3.5. in
y = {'one': 1, 'two': 2}
del y['three']
Output:KeyError: 'three'
y = {'one': 1, 'two': 2}
if 'three' in y:
del y['three']
print(y)
Output:{'one': 1, 'two': 2}
3.6. get
Returns the value associated with a key if the dictionary contains that key, in
case that the dictionary does not contain the key, you can specified a second
optional argument to return a default value, if the argument is not included get
method will return None.
y = {'one': 1, 'two': 2}
print(y.get('one'))
print(y.get('three'))
Output:1
None
3.7. setdefault
This method is similar to get method, it returns the value associated with a key
if the dictionary contains that key, but in case that the dictionary does not
Ms. ASHIKA MUTHANNA, SAPIENT COLLEGE PAGE 27
Ⅳ SEM BCA PYTHON
contain the key, this method will create a new element in the dictionary (key-
value pair), where the first argument in this method is the key, and the second
argument is the value. The second argument is optional, but if this is not
included, the value will be None.
y = {'one': 1, 'two': 2}
print(y.setdefault('three', '3'))
print(y.setdefault('two', 'dos'))
print(y)
Output:3
Dictionary Methods
Dictionary methods
Method Description
Populating Dictionaries
Addition of elements can be done in multiple ways. One value at a time can be
added to a Dictionary by defining value along with the key e.g. Dict[Key] =
„Value‟.
Note- While adding a value, if the key-value already exists, the value gets
updated otherwise a new Key with the value is added to the Dictionary.
Python3
Dict = {}
print(Dict)
Dict[0] = 'Geeks'
Dict[2] = 'For'
Dict[3] = 1
print(Dict)
# to a single Key
Dict['Value_set'] = 2, 3, 4
print(Dict)
Dict[2] = 'Welcome'
print(Dict)
print(Dict)
Output:
Empty Dictionary:
{}
Traversing Dictionaries
A dictionary is an ordered collection of items .Meaning a dictionary maintains
the order of its items.
We can iterate through dictionary keys one by one using a for loop.
country_capitals = {
"United States": "New York",
"Italy": "Naples"
}
print("----------")