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

chap 3 notes

The document provides an overview of strings and lists in Python, detailing their definitions, creation, and various operations such as indexing, slicing, and built-in methods. It explains string immutability and list mutability, along with operators for concatenation, repetition, and membership. Additionally, it lists several built-in functions for manipulating strings and lists, including methods for appending, sorting, and counting elements.

Uploaded by

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

chap 3 notes

The document provides an overview of strings and lists in Python, detailing their definitions, creation, and various operations such as indexing, slicing, and built-in methods. It explains string immutability and list mutability, along with operators for concatenation, repetition, and membership. Additionally, it lists several built-in functions for manipulating strings and lists, including methods for appending, sorting, and counting elements.

Uploaded by

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

Chapter 1: Python Revision Tour 3

String and List in Python Statement

What is String in Python?

A string is a sequence of characters. We can enclose characters in quotes (single,


double or triple.) For example: fruits=’Mango Apple Grapes’

Creating String /Types of string:

str1=’Hello world’
str2=”Python Programming”
str3=’’’Python
Programming’’’

Escape sequence character: \, \n, \t, \r, \f, \’, \’’.

*(An escape sequence character is represented as a string with one byte of memory.)
Empty String: An empty string is a string without any characters inside.

str=” ”, str=’ ‘

Multiple line String: Multiline strings are represented using triple quotes (‘’’ ‘’’) or
even single or double quotes.

Indexing in a string (Accessing Characters)

Accessing individual characters of the string by using the index value is called
indexing.

Traversing a String: Traversing a string means accessing all the elements of the string
one after the other by using the subscript / index value.

For loop:

First way: Second way:


While loop:

Special String Operators:

Concatenation: Concatenation refers to creating a new string by adding two strings. +


is the operator to join two string. Some Example: “Hello ”+”world”

Repetition or Replicate: By repetition of string we can create multiple copies of any


string.
* is the Operator for repetition. Some Example: “Hello” *3.

Membership: Membership operators used for checking whether a particular


character exists in the given string or not. Operators are: “in” and “not in”
Some Example:
“H” in “Hello” Gives True
“H” not in “Hello” Gives False.

Comparison Operators: Comparison operators are used to compare two strings.


Python compares strings using ASCII or UNICODE.
Some Example:
“Tim”==”tim” Gives False
“Freedom” > “Free” Gives True

String Slicing: Slicing is used to retrieve a subset of values. Chunk of characters can be
extracted from a string using slice operator. Example: var1 [start: end: step]
Some Example:
Str=”Save money”
str[1:3] gives “av”
str[:3] gives “Sav”

Updating: We can "update" an existing string by (re)assigning a variable to another


string.
Example: var1 [range] +”x”

String are Immutable:


Strings are immutable means that the element of the string cannot be changed after
it is created.
a=”student”
a [1] =”O” is invalid.

String Methods and Built-in-functions:

len() index() count() lstrip() join()


capitalize() isalpha() lower() rstrip() swapcase()
split() isalnum() islower() strip() partition()
replace() isdigit() upper() isspace() ord()
find() title() isupper() istitle() chr()

len() – This method returns the length of the string.


Santax: len(str)

capitalize() – This method return the exact copy of the string with the first letter in
uppercase.
Santax: str.capitalize()

split() – This method breaks up a string at the specified separator and returns a list of
substrings.
Santax: str.split(separator,maxsplit)

replace() – This function replaces all the occurrences of the old string with the new
string.
Santax: str.replace(old,new)

find() – This function is used to search the first occurrence of the substring in the
given string.
find() returns the lowest index of the substring if it is found in the given string. If the
substring is not found it returns -1.
Santax: str.find(sub,start,end)
index() – This function is quite similar to find() but raises an exception if the substring
is not present in the given string.
Syntax: str.index(substring, start, end)

isalpha() – This function checks for alphabets in an inputted string. It returns True if
the strings contains only letters, otherwise returns False.
Syntax: str.isalpha()

isalnum() – The isalnum() method returns True if all the characters are alphanumeric,
alphabet letters(a-z) and numbers (0-9).
Syntax: str.isalnum()

isdigit() – This function returns True if the string contains only digits, otherwise False.
Syntax: str.isdigit()

title() – This function returns the string with first letter of every word in the string in
uppercase and rest in lowercase.
Syntax: str.title()

count() – This function returns number of times substring occurs in the given string.
Syntax: str.count(substring, start, end)

lower() – This function converts all the uppercase letters in the string into lowercase.
Syntax: str.lower()

upper() – This function converts lowercase letters in the string into uppercase.

Syntax: str.upper()

islower() – This function returns True if all the letters in the string are in lowercase.
Syntax: str.islower()

isupper() – This function returns True if all the letters in the string are in uppercase.
Syntax: str.isupper()

lstrip() – This function returns the string after removing the spaces from left of the
string
Syntax: str.lstrip() or str.lstrip(char)
rstrip() – This function returns the string after removing the spaces from right of the
string
Syntax: str.rstrip() or str.rstrip(char)

strip() – This function returns the string after removing the spaces from both on left
and right of the string.
Syntax: str.strip()

isspace() – This function returns True if the string contains only whitespace
characters, otherwise return False.
Syntax: str.isspace()

istitle() – This function returns True if the string is properly in “title case”, else returns
False if the
String is not a “title-cased” string or an empty string.
Syntax: str.istitle()

join(sequence) – This function returns a string in which the string elements have
been joined by
a string separator.
Syntax: str.join(sequence)

swapcase() – This function converts all uppercase into lowercase and vice versa of
the given string. Syntax: str.swapcase()

partition (separator) – Partition function is used to convert the given string into a
tuple with three parts.
part1: substring before the separator,
part2: separator itself,
part3: a substring after the separator.

Syntax: str.partition(separator)

ord() – This function returns the ASCII/Unicode (ordinal) of the character.


Example: ord(“A”) gives 65

Chr() – This function returns the character represented by the inputted


Unicode/ASCII number.
Example: chr(65) gives “A”
What is List in Python?

A list is a collection of comma-separated values (items) within square brackets. Items


in a list need not of the same type. It stores data in ordered sequence.

Declaring/Creating List:

Syntax to creating List:


List_name=[“value1”, “value 2”, “value 3”, “value 4”]

Nested_List=[“value1”, [“value 2”, “value 3”], [“value 2”, “value 3”]]

Empty list=[ ]

Creating list from sequence, list(“Hello”)

Accessing List Elements:

Traversing a list: Traversing a list means accessing each element of a list. This can be
done by using either for or while looping statement.

Aliasing means: It mean nick name or alternate name of object. Means two object
with same id.
Copying list: It means to create clone or copy the list as different object. Means with
different id.

List Operators in Python


1) Concatenation: Concatenation or joining is a process in which multiple
sequences/lists can be combined together. ‘+’ is a symbol of concatenation operator.

2) Repetition/Replication/Multiply: This operator replicates the list for a specified


number of times and creates a new list. ‘*’ is a symbol of repetition operator.

3) Membership Operator: This operator used to check or test whether a particular


element or item is a member of any list or not. ‘in’ And ‘not in’ are the operators for
membership operator.

4) Indexing: Index is nothing but there is an index value for each item present in the
sequence or list. Example of nested list also.

5) Slicing Operator: This operator used to slice a particular range of a list or a


sequence. Slice is used to retrieve a subset of values.
Syntax: list [start : stop : step]

6) Comparing List: Python allows us to compare two lists. Each element is individually
compared in lexicographical (alphabetical or dictionary) order.

Built-in-functions and Methods of List

Append() Len() del statement


Extend() Sort() Remove()
Insert() Clear() Max()
Reverse() Count() Min()
Index() Pop() Sum()

append() – The append() method adds a single item to the end of the list. The item
can be of any data type, like, numbers, string, list, dictionary etc.
Syntax: list.append(item)
extend() – The extend() method adds one list at the end of another list. In other
words, all the items of a list are added at the end of an already created list.
Syntax: list.extend(list1)

insert() – The insert () function can be used to insert an element/object at a specified


index.
Syntax: list.insert(index_number,value)

reverse() – The reverse() function in python reverses the order of the elements in a
list.
Syntax: list.reverse()

index() – The index() function in python returns the index number of first matched
item from the list. if element is not present, value error is generated.
Syntax: list.index(item)

update list() – update means we can change item of list, because list is mutable, it is
also known as re-assignment.
Syntax: list[index]=new_value

len() – The len() function returns numbers of element in a list.


Syntax: len(list)

sort() – This function sorts the items of the list by default in ascending/increasing
order.
Syntax: list.sort()
Syntax: list.sort(reverse=True)

clear() – The clear() method removes all items from the list.
Syntax: list.clear()

count() – The count() method counts how many times an element has occurred in a
list and returns it.
Syntax: list.count(element)

pop() – It removes the element from the specified index and also returns the element
which was removed.
Syntax: list.pop(index)
Syntax: list.pop() – if no argument is provided pop() it will delete last element.
del statement – del statement removes the specified index from the list but does not
return the deleted value.
Syntax: del list[4]
Syntax: del list[2:4]

remove () – The remove() function is used to delete specified item.


Syntax: L1.remove (item)

max () – return the element with the maximum value from the list.
Syntax: max (list3)

min () – return the element with the minimum value from the list.
Syntax: min (list3)

sum () – return the sum of all element in a list.


Syntax: sum (list3)

You might also like