You are on page 1of 5

Python Cheat Sheet for String Manipulation, 4.

Comparison Operators word[3:],word[:3] will give ‘zing’,’ama’


List Manipulation, Tuples & Dictionaries “a”==”a” will return True word[:3]+word[3:] will give “amazing”
“a”!=”abc” will return True word[:-7]+word[-7:] will give “amazing”
String Manipulation (“ “or ‘ ‘) word[1:6:2] will give “mzn”
“A’!=”a” will return True
word[-7:-3:3] will give “az”
 Python string are immutable “ABC”==”abc” will return False word[::-2] will give “giaa”
 Each character/element has a unique “abc!=”Abc” will return True word[::-1] will give “gnizama”
index. You can access elements using ‘a’<’A’ will return
Characters False
Ordinal/ASCII
both forward and backward indexing ‘ABC’<’AB’ will return True
Values String Functions and Methods
‘abc’<=’ABCD’
‘0’ to ‘9’ 48will
to return
57 False 1. string.capitalize()
String Operators ‘A’ to ‘Z’ 65 toreturn
90 True
‘abcd’>’abcD’ will 2. string.find()
1. String Concatenation Operator + ‘a’ to ‘z’ 97 to 122 3. string.isalnum()
ord() , chr() and len() 4. string.isalpha()
“tea”+”pot” will result into “teapot” 5. string.isdigit()
‘1’+’1’ will result into ‘11’  ord(‘A’) will return 65 6. string.islower()
“a”+”0” will result into “a0”  chr(65) will return ‘A’ 7. string.isspace()
“123”+”abc” will result into “123abc”  s=”hello” 8. string.isupper()
9. string.lower()
“z”+3 will result into ERROR len(s) will return 5 10. string.upper()
2. String Replication Operator * 11.
String Slicing Liststring.lstrip()
Manipulation, []
“abc”*2 will result into “abcabc” 12. string.rstrip()
3*”bye” will result into “byebyebye”
word=”amazing”  List is a type of sequence like strings and
word[0:7] will give “amazing” tuples
“2”*”3” will result into ERROR
word[0:3] will give “ama”  Python lists are mutable
3. Membership Operators, in and not in
word[2:5] will give “azi”
“12” in “xyz” will return False Creating Lists
word[-7:-3} will give “amaz”
“12” not in “xyz” will return True word[-5:-1] will give “azin”
“jap” in Japan” will return False  Empty List, L=list()
word[:7} will give “amazing”
“Jap” in “Japan” will return True word[:5] will give “amazi”  Long List
“123” not in “12345” will return False word[3:] will give ‘zing’ Sqrs[0,1,4,9,16,25,36,49,64,81,100]
word[5:] will give “ng”  Nested List, L1=[3,4,[5,6],7]
1
 T=[1,2,3,4,5] Membership operators in, not in can
Non-equality Comparison in Lists
>>>l2=list(T) also be used
>>>l2 return [1,2,3,4,5] Comparison Result Reason
[1,2,8,9] < [9,1] True 1<9 List Functions and Methods
Accessing Lists [1,2,8,9]<[1,2,9,1] True 8<9 1. List.index()
vowels=[‘a’,’e’,’i’,’o’,’u’] [1,2,8,9]<[1,2,9,10] True 8<9 2. List.append()
[1,2,8,9]<[1,2,8,4] False 9
>>> vowels[0] return ‘a’ 3. List.extend()
>>>a=[2,3]
>>> vowels[4] return ‘u’ 4. List.insert()
>>>b=[2,3]
>>> vowels[-1] return ‘u’ 5. List.pop()
>>>c=[‘2’,’3’]
>>> vowels[-5] return ‘a’ 6. List.remove()
>>>d=[2.0,3.0]
7. List.clear()
Difference from String >>>e=[2,3,4]
8. List.count()
>>>a==b
Str=”hello” 9. List.reverse()
True
Str[3]=’x’ is INVALID List Operations 10. List.sort()
>>>a==c returns False
List1=[‘h’,’e’,’l’,’l’,’o’] Tuples, ()
Traversingisa VALID
List 1. Joining Lists
List1[3]=’x’  Tuples are sequences that are used to
>>>lst1=[1,3,5]
L=[‘p’,’y’,’t’,’h’,’o’,’n’] store a tuple of values of any type
>>>lst2=[6,7,8]
for a in L:  Tuples are immutable
>>>lst+lst2 return [1,3,5,6,7,8]
print(a)
2. Replicating Lists Creating Tuples

>>>lst1*3  (), empty tuple
Comparing List
>>>L1,L2=[1,2,3],[1,2,3]
>>>[1,3,5,1,3,5,1,3,5]  (1,2,3), tuple of integers
3. Slicing the Lists  (1,2,5,3.7,9), tuple of numbers
>>>L3=[1,[2,3]]
>>>lst=[10,12,14,20,22,24,30,32,34]  (‘a’,’b’,’c’), tuple of characters
>>>L1==L2 returns True
>>>seq=lst[3:-3] return [20,22,24]  (‘a’,’1’,’b’,3.5,’zero’), tuple of mixed
>>>L1==L3 returns False data types
>>>seq[1]=28 return [20,28,24]
>>>L1<L2 returns False  (‘One’,’Two’,’Three’), tuple of strings

2
1. The Empty Tuple >>>vowels[4] >>>a==b returns TRUE
T=tuple() ‘u’ >>>c=(‘2’,’3’)
2. Single Element Tuple >>>vowels[-5] >>>a==c returns FALSE
‘a’ Tuple Unpacking, tp1=(11,33,66,99)
>>>t=(1) Difference from Lists
>>>t a,b,c,d=tp1
1 L[i] =element, VALID in Lists c=77
3. Long Tuples T[i] =element, INVALID in Tuples tp1=(a,b,c,d)
>>>tp1
Sqrs=(0,1,4,9,16,25,36,49,64,81,100,
Similarity with Lists (11,33,77,99)
121,144,169,196,225)
4. Nested Tuples 1. len() Tuple Functions and Methods
T1(1,2,(3,4)) 2. Indexing and slicing
Creating Tuples from Existing 1. len() 2. max() 3. min()
3. Concatenation and Replication
Sequences Operators(+ and *)
>>>L= [‘a’,’e’,’i’,’o’,’u’] Dictionaries, {}
4. index() 5. count() 6.tuple()
4. Membership Operators
Tuple Operations  Dictionaries are mutable, unordered
>>>t2=tuple (L) 5. Comparison Operators
>>>t2 1. Joining Tuples 2. Replication collections with elements in the form of a
(‘a’,’e’,’i’,’o’,’u’) >>>tp1=(1,3,4) >>>tp1*3 key: value pairs that associate keys to
Reading Tuples from the user >>>tp2=(6,7,8) (1,3,4,1,3,4,1,3,4) values
T1=tuple(input(“Enter”)) >>>tpl+tp2 Creating a Dictionary
Enter: 234567 (1, 3, 4, 6, 7, 8)
>>>T1 3. Slicing the Tuples  To create a dictionary, you need to include
(‘2’,’3’,’4’,’5’,’6’,’7’) >>>tp1=(10,12,14,20,22,24,30,32) key: value pairs in curly braces as per
If more than one digit/character, use >>>seq=tp1(3:-3) following
eval(input()) (20,22) Teachers={“Dimple”:”Computer
>>>seq=[3:30] Science”,”Karen”:”Sociology”,”Harpreet”:”Math
Accessing Tuples
(20,22,24,30,32) ematics”,”Sabah”:”Legal Studies}
>>>vowels= (‘a’,’e’,’i’,’o’,’u’) 4. Comparing Tuples Key-Value Pair Key Value
>>>vowels[0] >>>a=(2,3) “Dimple”:”Computer “Dimple” “Computer
‘a’ >>>b-(2,3) Science” Science”
3
“Karen”:”Sociology” “Karen” “Sociology” >>>d.keys() >>>Employee=dict({“name”:”John”,”salary”:10000,
“Harpreet”:”Mathe “Harpreet” “Mathematics {“vowel5”,” vowel4”,” vowel3”, “age”:24}
matics” ” “vowel2”,”vowel1”} >>>Employee
“Subah”:”Legal “Subah” “Legal >>>d.values() {“salary”:10000,”age”:24,”name”:”John”}
Studies” Studies” {“a”,”e”,”i”,”o”,”u”} iii) Specify keys separately and corresponding
Accessing elements of a Dictionary \ values separately
Characteristics of a
>>>Employee=dict(zip((“name”:”salary”,”age”),
>>>teachers[“Karen”] Dictionary
(“John”,10000,24)))
Sociology 1. Unordered Set >>>Employee
>>>print(“Karen teaches”,teachers[“Karen”]) 2. Not a Sequence {“salary”:10000,”age”:24,”name”:”John”}
Karen teachers Sociology 3. Indexed by Keys, Not Numbers iv) Specify Key:value pairs separately in form of
>>>d={“vowel1”:”a”, 4. Keys must be unique sequences
“vowel2”:”e”,”vowel3”:”i”.”vowel4”:”o”,”vowel5”:” 5. Mutable >>>Employee=dict([[“name”,”John”],
u”} Working with Dictionaries
6. Internally stored as Mappings [“salary”,20000],[“age”,24]])
>>>print(d) Multiple Ways of creating Dictionaries >>>Employee
{“vowel1”:”a”,vowel2”:”e”,”vowel3”:”i”, Initializing a Dictionary {“salary”:10000,”age”:24,”name”:”John”}
”vowel4”:”o”,”vowel5”:”u”} Employee={“name”:”John”,”salary”:10000,
>>>d[“Vowel1”] ”age”:14} Adding elements in Dictionary
“a” Adding Key:value pairs to empty dictionary >>>Employee={“name”:”John”,”salary”:10000,
>>>d[“Vowel4”] i) Employees={} “age”:24}
“o” ii)Employee=dict() >>>Employee[“dept”]=”Sales”
Traversing a Dictionary Creating dictionary from name and value pairs >>>Employee
i) Specific Key:value pairs as keyword arguments to {“salary”:10000,”dept”:”Sales”,”age”:24,”name”:”J
for key in d: dict() ohn”}
print(key,”:”,d1[key]) Employee=dict(name=”John”,salary=10000,
age=24} Updating existing elements in Dictionary
Accessing Keys or >>>Employee >>> Employee={“name”:”John”,”salary”:10000,
Values Simultaneously {“salary”:10000,”age”:24,”name”:”John”} “age”:24}
ii) Specific comma-separated key:value pairs >>>Employee[“salary”]=20000
4
>>>Employee 8. split()
{“salary”:20000,”age”:24,”name”:”John} 9. dumps()[import JSON]

Deleting elements in Dictionary

>>>empl3
{“salary”:10000,”age”:24,”name”:”John”}
>>>del.empl3[“age”]
>>>empl3
{“salary:10000,”name”:”John”}
>>>empl3.pop(“name”)
“John”
>>>empl3
{“salary”:10000}

Checking for existence of a key

>>>”age” in empl3
False
>>>”salary” in empl3
True

Dictionary Functions and Methods

1. len()
2. clear()
3. get()
4. items()
5. keys()
6. values()
7. update()
5

You might also like