Вы находитесь на странице: 1из 70

PYTHON

Sequences:

1. Sequences are collection of items.


2. Item can be of any python type.
3. It can be ordered or unordered sequence.
4. Sequences may mutable or immutable.
Sequences:

1. Sring
2. Tuples
3. Sets
4. Lists
5. Dictionaries
STRING:

 1.String literals can be enclosed by


either double or single quotes.
2. Single quotes are more commonly
used.
3. String is a sequence of characters, for
e.g. “Hello” is a string of 5 characters.
4. String is an immutable object which
means it is constant and can cannot be
changed once it has been created.
FUNCTIONS OF STRING:

1. Capitalize() :
The capitalize() function doesn't take any
parameter.
The capitalize() function returns a string with
first letter capitalized. It doesn't modify the old
string.

The syntax of capitalize() is:


string.capitalize()
example:
string = "python is awesome.”
capitalized_string = string.capitalize()
print('Old String: ', string)
print('Capitalized String:', capitalized_string)

Output:
Old String: python is awesome.
Capitalized String: Python is awesome.

2. Centre():
Pads string with specified character.
The center() method takes two arguments:
width - length of the string with padded characters
fillchar (optional) - padding character
The fillchar argument is optional. If it's not
provided, space is taken as default argument.

The syntax of center() method is:


string.center(width[, fillchar])

Example:
string = "Python is awesome“
new_string = string.center(24)
print("Centered String: ", new_string)
Output:
Centered String: Python is awesome

3. Casefold():
The casefold() method is removes all case
distinctions present in a string. It is used for
caseless matching, i.e. ignores cases when
comparing.
The syntax of casefold() is:
string.casefold()
Example:
firstString = "der Fluß“
secondString = "der Fluss“
# ß is equivalent to ss
if firstString.casefold() == secondString.casefold():
print('The strings are equal.')
else:
print('The strings are not equal.')
Output:
The strings are equal.
4. Count():
The string count() method returns the number of
occurrences of a substring in the given string.
In simple words, count() method searches the
substring in the given string and returns how many
times the substring is present in it.
It also takes optional parameters start and end to
specify the starting and ending positions in the
string respectively.
The syntax of count() method is:
string.count(substring, start=..., end=...)
Example:
string = "Python is awesome, isn't it?“
substring = "is“
count = string.count(substring)
# print count
print("The count is:", count)
Output:
The count is: 2

5. Endswith()
The endswith() method returns True if a string
ends with the specified suffix. If not, it returns
False.
The syntax of endswith() is:
str.endswith(suffix[, start[, end]])
Example:
text = "Python is easy to learn.“
result = text.endswith('to learn')
# returns False
print(result)result = text.endswith('to learn.')
# returns True
print(result)
Output:
False
True
6. Expandtabs()
The expandtabs() method returns a copy of string
with all tab characters '\t' replaced with
whitespace characters until the next multiple of
tabsize parameter.
The syntax of expandtabs() method is:
string.expandtabs(tabsize)

Example:
str = 'xyz\t12345\tabc‘
# no argument is passed
# default tabsize is 8
result = str.expandtabs()
print(result)
Output:
xyz 12345 abc

7. Encode():
Using string's encode() method, you can convert
unicoded strings into any 
encodings supported by Python. By default,
Python uses utf-8 encoding.
The syntax of encode() method is:
string.encode(encoding='UTF-8',errors='strict')
Example:
# unicode string string = 'pythön!‘
# print string
print('The string is:', string)
# default encoding to utf-8
string_utf = string.encode()
# print result
print('The encoded version is:', string_utf)
Output:
The string is: pythön!
The encoded version is: b'pyth\xc3\xb6n!'
8. find():
The find() method returns the lowest index of the
substring (if found). If not found, it returns -1.
The syntax of find() method is:
str.find(sub[, start[, end]] )
Example:
quote = 'Let it be, let it be, let it be‘
result = quote.find('let it')
print("Substring 'let it':", result)
result = quote.find('small')
print("Substring 'small ':", result)
if (quote.find('be,') != -1):
print("Contains substring 'be,'")
else:
print("Doesn't contain substring")
Output:
Substring 'let it': 11
Substring 'small': -1
Contains substring 'be,‘

9. Index():
The index() method returns the index of a
substring inside the string (if found). If the
substring is not found, it raises an exception.
The syntax of index() method for string is:
str.index(sub[, start[, end]] )
Example:
sentence = 'Python programming is fun.‘
result = sentence.index('is fun')
print("Substring 'is fun':", result)
result = sentence.index('Java')
Output:
Substring 'is fun': 19
Traceback (most recent call last):
File "...", line 6, in result = sentence.index('Java')
ValueError: substring not foundprint("Substring
'Java':", result)
10.Isalnum():
The isalnum() method returns True if all characters
in the string are alphanumeric (either alphabets or
numbers). If not, it returns False.
The syntax of isalnum() is:
string.isalnum()
Example:
name = "M234onica“
print(name.isalnum())
name = "M3onica Gell22er”
print(name.isalnum())
Name= "Mo3nicaGell22er“
print(name.isalnum())
name = "133“
print(name.isalnum())
Output:
True
False
True
True

11. Isalpha():
The isalpha() method returns True if all
characters in the string are alphabets. If not, it
returns False.
The syntax of isalpha() is:
string.isalpha()
Example:
name = "Monica“
print(name.isalpha())
name = "Monica Geller“
print(name.isalpha())
name = "Mo3nicaGell22er“
print(name.isalpha())
Output:
True
False
False
12. isdecimal():
The isdecimal() method returns True if all
characters in a string are decimal characters. If not,
it returns False.
The syntax of isdecimal() is
string.isdecimal()

Example:
s = "28212“
print(s.isdecimal())
Output:
True
13. isdigit():
The isdigit() method returns True if all characters
in a string are digits. If not, it returns False.
The syntax of isdigit() is
string.isdigit()

Example():
s = "28212“
print(s.isdigit())
Output:
true
14. isidentifier():
The isidentifier() method returns True if the string
is a valid identifier in Python. If not, it returns
False.
The syntax of isidentifier() is:
string.isidentifier()

Example:
str = 'Python‘
print(str.isidentifier())
str = 'Py thon‘
print(str.isidentifier())
str = '22Python‘
print(str.isidentifier())
Output:
True
False
False

15. islower():
The islower() method returns True if all alphabets
in a string are lowercase alphabets. If the string
contains at least one uppercase alphabet, it returns
False.
The syntax of islower() is:
string.islower()
Example:
s = 'this is good‘
print(s.islower())
Output:
True

16. isnumeric():
The isnumeric() method returns True if all
characters in a string are numeric characters. If not,
it returns False.
The syntax of isnumeric() is
string.isnumeric()
Example:
s = '1242323'
print(s.isnumeric())
Output:
True

17. isprintable():
The isprintable() methods returns True if all
characters in the string are printable or the string
is empty. If not, it returns False.
The syntax of isprintable() is:
string.isprintable()

Example:
s = 'Space is a printable‘
print(s)
print(s.isprintable())
Output:
Space is a printable
True

18. isspace():
The isspace() method returns True if there are only
whitespace characters in the string. If not, it return
False.
The syntax of isspace() is:
string.isspace()

Example:
s = ' \t‘
print(s.isspace())
Output:
True

19. isupper():
The string isupper() method returns whether or not
all characters in a string are uppercased or not.
The syntax of isupper() method is:
string.isupper()

Example:
string = "THIS IS GOOD!“
print(string.isupper());
Output:
True
20. swapcase():
The string swapcase() method converts all
uppercase characters to lowercase and all
lowercase characters to uppercase characters of the
given string, and returns it.
The format of swapcase() method is:
string.swapcase()

Example:
string = "THIS SHOULD ALL BE LOWERCASE.“
print(string.swapcase())
string = "this should all be uppercase.“
print(string.swapcase())
Output:
this should all be lowercase.
THIS SHOULD ALL BE UPPERCASE.

21. strip():
The strip() method returns a copy of the string
with both leading and trailing characters removed
(based on the string argument passed).

Example:
string = ' xoxo love xoxo ‘
print(string.strip())
print(string.strip(' xoxoe'))
Output:
xoxo love xoxo
Lov

22. partition():
The partition() method splits the string at the first
occurrence of the argument string and returns a
tuple containing the part the before separator,
argument string and the part after the separator.
The syntax of partition() is:
string.partition(separator)

Example:
string = "Python is fun“
print(string.partition('is '))
Output:
('Python ', 'is ', 'fun')

23. replace():
The replace() method returns a copy of the string
where all occurrences of a substring is replaced
with another substring.
The syntax of replace() is:
str.replace(old, new [, count])

Example:
song = 'cold, cold heart‘
print (song.replace('cold', 'hurt'))
Output:
hurt, hurt heart

24. split():
The split() method breaks up a string at the
specified separator and returns a list of strings.
The syntax of split() is:
str.split([separator [, maxsplit]])

Example:
text= 'Love thy neighbor‘
print(text.split())
Output:
['Love', 'thy', 'neighbor']
25. startswith():
The startswith() method returns True if a string
starts with the specified prefix(string). If not, it
returns False.
The syntax of startswith() is:
str.startswith(prefix[, start[, end]])
Example:
text = "Python is easy to learn.“
result = text.startswith('is easy')
print(result)
result = text.startswith('Python is ')
print(result)
Output:
False
True
TUPLES

1. A tuple is a sequence of immutable Python


Objects.
2. Tuples use parentheses ()
3. Tuples are ordered immutable Sequences.
4. It is like an read only Array.
5. It can not be Sort.
6. Tuples can be added to get a new Tuple.
FUNCTIONS OF TUPLES

1. len() :
This function is used to get the number of elements
inside any tuple.

Example:
t = (1, 2, 3)
print len(t)
Output:
3
2. max() and min() :
To find the maximum value in a tuple, we can use
the max() function, while for finding the minimum
value, min() function can be used.

Example:
t = (1, 4, 2, 7, 3, 9)
print max(t)
print min(t)
Output:
9
1
3. cmp():
This is used to compare two tuples. It will return
either 1, 0 or -1, depending upon whether the two
tuples being compared are similar or not.
if T1 > T2, then cmp(T1, T2) returns 1
if T1 = T2, then cmp(T1, T2) returns 0
if T1 > T2, then cmp(T1, T2) returns -1

4. count():
The count() method returns the number of
occurrences of an element in a tuple.
The syntax of count() method is:
tuple.count(element)
Example:
vowels = ('a', 'e', 'i', 'o', 'i', 'o', 'e', 'i', 'u')
count = vowels.count('i')
print('The count of i is:', count)
Output:
The count of i is: 3

5. index():
The index() method searches an element in a tuple
and returns its index.
The syntax of index() method for Tuple is:
tuple.index(element)
Example:
vowels = ('a', 'e', 'i', 'o', 'i', 'u’)
index = vowels.index('e')
print('The index of e:', index)
Output:
The index of e: 1

6. reversed():
The reversed() method returns the reversed
iterator of the given sequence.
The syntax of reversed() is:
reversed(seq)
Example:
seqString = 'Python‘
print(list(reversed(seqString)))
Output:
['n', 'o', 'h', 't', 'y', 'P']

7. sorted():
The sorted() method returns a sorted list from
the given iterable.
The syntax of sorted() method is:
sorted(iterable[, key][, reverse])
Example:
pyList = ['e', 'a', 'u', 'o', 'i']
print(sorted(pyList))
Output:
['a', 'e', 'i', 'o', 'u']

8. sum():
The sum() function adds the items of an iterable
and returns the sum.
The syntax of sum() is:
sum(iterable, start)
Example:
numbers = [2.5, 3, 4, -5]
numbersSum = sum(numbers)
print(numbersSum)
Output:
4.5

9. tuple():
The tuple() built-in is used to create a tuple in
Python.
The syntax of tuple() is:
tuple(iterable)
Example:
t1 = tuple('Python')
print('t1=',t1)
Output:
t1= ('P', 'y', 't', 'h', 'o', 'n')
SETS

1. Sets are unordered immutable sequences of


unique elements.
2. Discard the duplicate value in sets.
3. Set are not iterate.
FUNCTIONS OF SET

1. remove():
The remove() method searches for the given
element in the set and removes it.
The syntax of remove() method is:
set.remove(element)

Example:
language = {'English', 'French', 'German'}
language.remove('German')
print('Updated language set: ', language)
Output:
Updated language set: {'English', 'French'}

2. add():
The set add() method adds a given element to a
set. If the element is already present, it doesn't
add any element.
The syntax of add() method is:
set.add(elem)

Example:
vowels = {'a', 'e', 'i', 'u'}
vowels.add('o')
print('Vowels are:', vowels)
Output:
Vowels are: {'a', 'i', 'o', 'u', 'e'}

3. copy():
The copy() method returns a shallow copy of the
set.
Example:
numbers = {1, 2, 3, 4}
new_numbers = numbers
new_numbers.add('5')
print('numbers: ', numbers)
print('new_numbers: ', new_numbers)
Output:
numbers: {1, 2, 3, 4, '5'}
new_numbers: {1, 2, 3, 4, '5'}
4. clear():
The clear() method removes all elements from the
set.
The syntax of clear() method is:
set.clear()
Example:
vowels = {'a', 'e', 'i', 'o', 'u'}
print('Vowels (before clear):', vowels)
vowels.clear()
print('Vowels (after clear):', vowels)
Output:
Vowels (before clear): {'e', 'a', 'o', 'u', 'i'}
Vowels (after clear): set()
5. difference():
The difference() method returns the set difference
of two sets.
The syntax of difference() method in Python is:
A.difference(B)
Example:
A = {'a', 'b', 'c', 'd'}
B = {'c', 'f', 'g'}
print(A.difference(B))
print(B.difference(A))
Output:
{'b', 'a', 'd'}
{'g', 'f'}
6. intersection():
The intersection() method returns a new set with
elements that are common to all sets.
The syntax of intersection() in Python is:
A.intersection(*other_sets)
Example:
A = {2, 3, 5, 4}
B = {2, 5, 100}
C = {2, 3, 8, 9, 10}
print(B.intersection(A))
print(B.intersection(C))
print(A.intersection(C))
print(C.intersection(A, B))
Output:
{2, 5}
{2}
{2, 3}
{2}

7. isdisjoint():
The isdisjoint() method returns True if two sets
are disjoint sets. If not, it returns False.
The syntax of isdisjoint() is:
set_a.isdisjoint(set_b)
Example:
A = {1, 2, 3, 4}
B = {5, 6, 7}
C = {4, 5, 6}
print('Are A and B disjoint?', A.isdisjoint(B))
print('Are A and C disjoint?', A.isdisjoint(C))
Output:
Are A and B disjoint? True
Are A and C disjoint? False

8. issubset():
The issubset() method returns True if all
elements of a set are present in another set
(passed as an argument). If not, it returns False.
Example:
A = {1, 2, 3}
B = {1, 2, 3, 4, 5}
print(A.issubset(B))
Output:
True

9. union():
The union() method returns a new set with
distinct elements from all the sets.
The syntax of union() is:
A.union(*other_sets)
Example:
A = {'a', 'c', 'd'}
B = {'c', 'd', 2 }
print('A U B =', A.union(B))
Output:
A U B = {2, 'a', 'd', 'c'}

10. update():
The update() adds elements from a set (passed as
an argument) to the set (calling the update()
method).
The syntax of update() is:
A.update(B)
Example:
A = {'a', 'b'}
B = {1, 2, 3}
result = A.update(B)
print('A =',A)
Output:
A = {'a', 1, 2, 3, 'b'}
LIST

1. Lists are ordered mutable sequences like


Array.
2. Lists can be compared to heterogeneous
array.
3. Lists can be increased or decreased
dynamically.
FUNCTIONS OF LIST

1. append():
The append() method adds an item to the end of
the list.
The syntax of append() method is:
list.append(item)
Example:
animal = ['cat', 'dog', 'rabbit']
animal.append('guinea pig')
print('Updated animal list: ', animal)
Output:
Updated animal list: ['cat', 'dog', 'rabbit', 'guinea
pig']
2. extend():
The extend() extends the list by adding all items
of a list (passed as an argument) to the end.
The syntax of extend() method is:
list1.extend(list2)
Example:
language = ['French', 'English', 'German']
language1 = ['Spanish', 'Portuguese']
language.extend(language1)
print('Language List: ', language)
Output:
Language List: ['French', 'English', 'German',
'Spanish', 'Portuguese']
3. insert():
The insert() method inserts the element to the
list at the given index.
The syntax of insert() method is
list.insert(index, element)

Example:
vowel = ['a', 'e', 'i', 'u']
vowel.insert(3, 'o')
print('Updated List: ', vowel)
output:
Updated List: ['a', 'e', 'i', 'o', 'u']
4. pop():
The pop() method removes and returns the
element at the given index (passed as an
argument) from the list.
The syntax of pop() method is:
list.pop(index)

Example:
language = ['Python', 'Java', 'C++', 'French', 'C']
return_value = language.pop(3)
print('Return Value: ', return_value)
print('Updated List: ', language)
Output:
Return Value: French
Updated List: ['Python', 'Java', 'C++', 'C']
5. index():
The index() method searches an element in the
list and returns its index.
The syntax of index() method for list is:
list.index(element)

Example:
vowels = ['a', 'e', 'i', 'o', 'i', 'u']
index = vowels.index('e')
print('The index of e:', index)
Output:
The index of e: 1
DICTIONARY
1. A dictionary is a collection which is
unordered, changeable and indexed.
2. Dictionaries are written with curly
brackets
3. They have keys and values.
Example:
thisdict ={ "apple": "green","banana": "yellow",
"cherry": "red"}
print(thisdict)
Output:
{'apple': 'red', 'banana': 'yellow', 'cherry': 'red'}
FUNCTIONS OF DICTIONARY
1. fromkeys():
The fromkeys() method creates a new dictionary
from the given sequence of elements with a value
provided by the user.
The syntax of fromkeys() method is:
dictionary.fromkeys(sequence[, value])

Example:
keys = {'a', 'e', 'i', 'o', 'u' }
vowels = dict.fromkeys(keys)
print(vowels)
Output:
{'a': None, 'u': None, 'o': None, 'e': None, 'i': None}

2. get():
The get() method returns the value for the
specified key if key is in dictionary.
The syntax of get() is:
dict.get(key[, value])

Example:
person = {'name': 'Phill', 'age': 22}
print('Name: ', person.get('name'))
print('Age: ', person.get('age'))
Output:
Name: Phill
Age: 22

3. items():
The items() method returns a view object that
displays a list of dictionary's (key, value) tuple
pairs.
The syntax of items() method is:
dictionary.items()

Example:
sales = { 'apple': 2, 'orange': 3, 'grapes':4}
print(sales.items())
Output:
dict_items([('apple', 2), ('orange', 3), ('grapes', 4)])

4. keys():
The keys() method returns a view object that
displays a list of all the keys in the dictionary
The syntax of keys() is:
dict.keys()

Example:
person = {'name': 'Phill', 'age': 22, 'salary': 3500.0}
print(person.keys())
Output:
dict_keys(['name', 'salary', 'age'])

5. setdefault():
The setdefault() method returns the value of a
key (if the key is in dictionary). If not, it inserts
key with a value to the dictionary.
The syntax of setdefault() is:
dict.setdefault(key[, default_value])

Example:
person = {'name': 'Phill', 'age': 22}
age = person.setdefault('age')
print('person = ',person)
print('Age = ',age)
Output:
person = {'name': 'Phill', 'age': 22}
Age = 22

6. values():
The values() method returns a view object that
displays a list of all the values in the dictionary.
The syntax of values() is:
dictionary.values()

Example:
sales = { 'apple': 2, 'orange': 3, 'grapes': 4 }
print(sales.values())
Output:
dict_values([2, 4, 3])
THANK YOU

Вам также может понравиться