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

Summary Python 1

Uploaded by

TUSHAR LAKHER
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views

Summary Python 1

Uploaded by

TUSHAR LAKHER
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 36

REGEX


.: Matches any single character except newline
 ^: Matches the start of the string
 $: Matches the end of the string
 *: Matches 0 or more repetitions
 +: Matches 1 or more repetitions
 ?: Matches 0 or 1 repetitions
 \: Used to escape various characters including all metacharacters

EXAMPLES:
Here are some ways you can use the re module with the above metacharacters:
1. Basic matching:

import re
pattern = r"Cookie"
sequence = "I want a Cookie"
if re.match(pattern, sequence):
print("Match!")
else: print("Not a match!")
Here the match() function checks for a match of the string in the beginning. If we have the word "Cookie" at the
start of the string, it will return a Match object. Otherwise, it will return None.
2. Searching:

import re
pattern = r"Cook"
sequence = "I want a Cookie"
print(re.search(pattern, sequence))
The search() function scans through the string, looking for any location where the REGEX pattern matches. If it
finds a match, it returns a match object. Otherwise, it returns None.
3. Finding all instances:

import re
pattern = r"Cook"
sequence = "Cookie Cooker cooks cookies while looking cool"
print(re.findall(pattern, sequence))
In this case, findall() function returns all non-overlapping matches of pattern in string, as a list of strings.
These are just basics! Regular expressions can get much more complex and powerful, allowing you to define
intricate patterns to match.
Remember, when you're writing regular expressions in Python, we typically use raw strings (r"mystring"). This
makes writing and interpreting them easier, since you don't have to worry about Python also using the backslash
as an escape character in its regular strings.

1. Using ^ to match the start of the string

print(re.search(r'^Eat', "Eat cake!")) # will match as 'Eat' is at the start


print(re.search(r'^cake', "Eat cake!")) # will not match as 'cake' is not at the start
2. Using $ to match the end of the string
print(re.search(r'cake$', "Eat cake")) # will match as 'cake' is at the end
print(re.search(r'cake$', "Eat cake and cookies")) # will not match as 'cake' is not at the end
3. * to match 0 or more repetitions
content_copy Copy cod

print(re.search(r'ca*k', 'cake')) # matches as there's one 'a' before 'k'


print(re.search(r'ca*k', 'ck')) # matches as there's zero 'a' before 'k'
4. + to match 1 or more repetitions

print(re.search(r'ca+k', 'cake')) # matches as there's one 'a' before 'k'


print(re.search(r'ca+k', 'ck')) # will not match as there's zero 'a' before 'k'
5. ? to match 0 or 1 repetitions

print(re.search(r'ca?k', 'cake')) # matches as there's one 'a' before 'k'


print(re.search(r'ca?k', 'ck')) # matches as there's zero 'a' before 'k'
6. \d to match any decimal digit

print(re.search(r'c\d+k', 'c2k')) # matches as there's a digit between 'c' and 'k'


print(re.search(r'c\d+k', 'cake')) # will not match as there's no digit between 'c' and 'k'
7. \D to match any non-digit character

print(re.search(r'c\D+k', 'cake')) # matches as there's a non-digit between 'c' and 'k'


print(re.search(r'c\D+k', 'c2k')) # will not match as there's a digit between 'c' and 'k'
8. \s to match any whitespace character

print(re.search(r'Eat\sCake', 'Eat Cake')) # matches as there's a whitespace


print(re.search(r'Eat\sCake', 'EatCake')) # will not match as there's no whitespace
9. \S to match any non-whitespace character

print(re.search(r'c\Sk', 'c2k')) # matches as there's a non-whitespace


print(re.search(r'c\Sk', 'c k')) # will not match as there's a whitespace
10. \w to match any alphanumeric character or underscore

print(re.search(r'c\wk', 'c2k')) # matches as there's a digit


print(re.search(r'c\wk', 'c_k')) # matches as there's an underscore
11. \W to match any non-alphanumeric character

print(re.search(r'c\Wk', 'c*k')) # matches as there's a non-alphanumeric character


print(re.search(r'c\Wk', 'c2k')) # will not match as there's a alphanumeric character
12. [] to indicate a set of characters

print(re.search(r'c[a2]k', 'c2k')) # matches as '2' is in the set


print(re.search(r'c[a2]k', 'cak')) # matches as 'a' is in the set
13. Complete the set [] with a -

print(re.search(r'c[a-z]k', 'cak')) # matches as 'a' falls in 'a-z'


print(re.search(r'c[a-z]k', 'c2k')) # will not match as '2' isn't in 'a-z'
14. Escape special characters with \

print(re.search(r'c\.k', 'c.k')) # matches as 'c.k' exactly matches pattern


print(re.search(r'c\.k', 'c2k')) # will not match as '.' is not in the string
15. Using re.IGNORECASE to search ignoring text case

print(re.search(r'cake', 'CaKe', re.IGNORECASE)) # matches ignoring the text case


16. re.sub() to substitute matches

print(re.sub(r'colour', 'color', 'I love the colour red')) # substitutes 'colour' with 'color'
17. re.split() to split by a pattern

print(re.split(r'\d+', 'split on 2 numbers 3')) # splits the string by digits


18. re.compile() to reuse regex

pattern = re.compile(r'cookie', re.IGNORECASE)


print(pattern.search("I am a Cookie")) # reuses compiled regex
19. \b to specify word boundary

print(re.search(r'\bEat', 'Eat cake!')) # matches 'Eat' as a whole word


print(re.search(r'\bEat', 'Peaceful Eats')) # will not match as 'Eat' is not a whole word
20. (pattern) to capture groups

match = re.search(r'(c\wk)', 'c2k') # matches and captures 'c2k'


print(match.group(1)) # retrieves first captured group

1. Negated character class [^]

print(re.findall(r'[^aeiou ]', 'Hello, world!'))


# Finds all consonants and punctuation in a string.
2. Quantified group {m,n}

print(re.search(r'ba{2,4}', 'baaa')) # Matches 'baaa'


print(re.search(r'ba{2,4}', 'ba')) # Doesn't match
3. Lazy quantifiers *?, +?, ??, {m,n}?

print(re.search(r'<.*?>', '<a> <b>')) # Uses *? to match as little as possible


print(re.search(r'a{3,5}?', 'aaaaa')) # Uses {m,n}? to match as little as possible
4. Positive look ahead (?=)

print(re.search(r'fox(?= hunts)', 'The quick fox hunts')) # Matches 'fox' if followed by ' hunts'
5. Negative look ahead (?!

print(re.search(r'fox(?! hunts)', 'The quick fox')) # Matches 'fox' if not followed by ' hunts'
6. Positive look behind (?<=

print(re.search(r'(?<=\bThe\b).+', 'The quick fox')) # Matches ' quick fox' if it is preceded by 'The'
7. Negative look behind (?<!

print(re.search(r'(?<!\bThe\b).+', ' quick fox')) # Matches ' quick fox' if it is not preceded by 'The'
8. Word boundary \b, non-word boundary \B

print(re.findall(r'\bfox\b', 'fox thefox quickfox')) # Matches 'fox' as a whole word


print(re.findall(r'\Bfox\B', 'fox thefox quickfox')) # Matches 'fox' inside 'thefox' and 'quickfox'
9. Metacharacter escapes \, \Q...\E, etc.

print(re.search(r'\$', 'Price: $5')) # Escape $ with \


10. Alternation |

print(re.search(r'cat|dog', 'I like dogs')) # Matches 'dog'


11. Capture groups \1, \2, etc.

print(re.sub(r'(\d+)-(\d+)-(\d+)', r'\3-\1-\2', '2021-05-15')) # Rearranges date formats


12. Named groups (?P<name>)

print(re.search(r'(?P<animal>cat|dog)', 'I like dogs')) # Matches 'dog' and names the group 'animal'
13. Named backreferences \g<name>

print(re.sub(r'(?P<year>\d+)-(?P<month>\d+)-(?P<day>\d+)', r'\g<day>-\g<month>-\g<year>', '2021-05-15')) #


Rearranges date formats
14. Non-capturing groups (?:)

print(re.search(r'(?:cat|dog)', 'I like dogs')) # Matches 'dog' but does not create a backreference
15. Atomic groups (?>)

print(re.search(r'(?>cat|catter)pillar', 'catterpillar')) # Matches 'catterpillar'


16. Environment variables (?i), (?m), etc.
print(re.search(r'(?i)cat', 'CAT')) # Matches 'CAT' in a case-insensitive manner
17. Comments (?#)

print(re.search(r'fox(?#Matches fox)', 'The quick fox')) # Matches 'fox' (comments are ignored)
18. Unicode property escapes \p, \P

print(re.search(r'\p{Lu}', 'HELLO')) # Matches 'H' (the first Unicode uppercase letter)


19. Grapheme cluster \X

print(re.findall(r'\X', 'naïve')) # Matches ['n', 'a', 'ï', 'v', 'e'] (includes the accent as part of 'ï')
20. Sub-routines (?(DEFINE)...), \g<name>, etc.

pattern = re.compile(r'''
(?(DEFINE)
(?P<letter>[a-z])
)
\g<letter>+
''', re.VERBOSE)
print(pattern.search('hello')) # Matches 'hello'

1. Matching exact number of repetitions {m}

print(re.search(r'ha{2}', "haha")) # Matches 'haha' since 'a' appears twice successive to 'h'
2. Matching at least n repetitions {n,}

print(re.search(r'a{2,}', "aa")) # Matches because 'a' appears at least twice


3. Matching repetitions between m and n {m,n}

print(re.search(r'a{2,3}', "aaa")) # Matches 'aaa' since 'a' appears three times


4. Matching either OR condition |

print(re.search(r"cat|dog", "cat")) # Matches 'cat' since it is an OR condition


5. Matching any character in character class []

print(re.search(r'gr[ae]y', 'gray')) # Matches 'gray' since 'a' appears in character class


6. Matching any digit \d

print(re.findall(r'\d', '123')) # Matches ['1', '2', '3'] since these are digits
7. Matching any non-digit \D

print(re.findall(r'\D', '123abc')) # Matches ['a', 'b', 'c'] since these are non-digits
8. Matching any white space character \s
print(re.search(r'Eat\sCake', 'Eat Cake')) # Matches 'Eat Cake' since there is a whitespace character
9. Matching any non-white space character \S

print(re.search(r'\S', 'abc def')) # Matches 'a', since it is a non-white space character


10. Matching any alphanumeric \w

print(re.search(r'\w', 'abc123')) # Matches 'a', since it is part of alphanumeric


11. Matching any non-alphanumeric \W

print(re.search(r'\W', 'abc def')) # Matches ' ', since it is non-alphanumeric


12. \b for word boundary

print(re.findall(r'\bThe\b', 'The cat in The hat')) # Matches both 'The' since they are whole words separated by
word boundaries
13. \A for matching only at start of string

print(re.search(r'\AThe', 'The cat')) # Matches because 'The' is at the beginning of the string
14. \Z for matching only at end of string

print(re.search(r'cat\Z', 'The cat')) # Matches because 'cat' is at the end of the string
15. Matching a character n number of times until another character is met .*?

print(re.findall(r'^a.*?b', 'acb')) # Matches because 'b' is met after 'a' appears


16. Substituting first match using re.sub()

print(re.sub(r'\W', '', 'hello, world!')) # Substitutes non-alphanumeric characters with no character


17. Substituting all matches using re.sub()

print(re.sub(r'\W', '', 'hello, world!', flags=re.IGNORECASE)) # Substitutes non-alphanumeric characters in case-


insensitive manner
18. Using compiled pattern

pattern = re.compile(r"Cookie", re.IGNORECASE)


print(pattern.sub("Cream", "I want a Cookie")) # Substitutes 'Cookie' with 'Cream'
19. Searching pattern in multiple lines

print(re.search(r"^abc", "123\nabc", flags=re.MULTILINE)) # Matches 'abc' because of multiline flag


20. Splitting a string re.split()
print(re.split('\W+', 'Words, words , Words')) # Splits string at every non-alphanumeric character

Certainly, here are more regex examples and explanations of their functionality:
1. Inverse Matching with ^

print(re.findall(r'[^A-Za-z ]', "Hello World 123!")) # Find all characters that are not A-Z, a-z or a space
2. Matching 0 or More Repetitions with *

print(re.search(r'fo*', "foo")) # Matches 'foo'


3. Pattern Matching with Alphabets and Digits a-z, A-Z, 0-9

print(re.search(r'[A-Za-z0-9]', 'Hello1')) # Matches 'H' - the first occurrence of the pattern


4. Capturing and Grouping multiple patterns ()

print(re.match(r'(abc|def|ghi)', 'abcdef').groups()) # Matches 'abc'


5. Match Any Single Character Except newline \.

print(re.search(r'c.k', 'cak')) # Matches 'cak'


6. Bind the re functions into the objects using re.compile

pattern = re.compile(r'[A-Z]')
print(pattern.search('Hello')) # Matches 'H'
7. Escape Special Characters \\

print(re.search(r'\$', '1$')) # Matches '$'


8. Find the start of the String ^

print(re.search(r'^H', 'Hello')) # Matches 'H'


9. Matching Dates with \d

print(re.search(r'\d{2}-\d{2}-\d{4}', 'Date: 10-12-2021')) # Matches '10-12-2021'


10. Non-digits with \D

print(re.search(r'\D', '123 Rocky 456')) # Matches ' ' the first non digit character
11. match() to Determine if the RE matches at the start of the string

print(re.match("c", "abcdef")) # No match


12. Using Compilation Flags like IGNORECASE, MULTILINE, etc

print(re.findall(r'abc', 'ABCabc', re.IGNORECASE)) # Matches both 'ABC' and 'abc'


13. Positive Look Ahead ?=, Negative Look Ahead ?!
print(re.search(r'fox(?= hunt)', 'fox hunts quickly')) # Matches 'fox' in 'fox hunts'
14. Non-Capturing and Capturing Groups (?:), ()

print(re.findall(r'(?:a)(b)', 'abc abc')) # Matches ['b', 'b']


15. Greedy (.*) vs Non-Greedy(.*?) Quantifiers

print(re.findall(r'a.*b', 'ab ac')) # Greedy: Matches 'ab ac'


16. Replacing text with re.sub()

print(re.sub(r'dog', 'cat', 'I have a dog')) # Replaces 'dog' with 'cat'


17. Selecting from Multiple Options [abc]

print(re.findall(r'[abc]', 'abcdef')) # Matches ['a', 'b', 'c']


18. Name your match (?P<name>)

match = re.search('(?P<word>\w+)', 'hello')


print(match.group('word')) # Matches 'hello'
19. Decoding percent-encoded characters

print(re.sub(r'%([0-9a-fA-F]{2})', lambda m: chr(int(m.group(1), 16)), 'hello%20world')) # Decodes to 'hello world'


20. Matching HTML Tags

print(re.findall(r'<(.+?)>', '<html><body><h1>Hello world!</h1></body></html>')) # Matches ['html', 'body'


--------------------------------------------------------------------------------------------------------------------------------------------------------

PRACTISE CODING TOPIC WISE

String

1. Write a function to reverse a string.


2. Implement a function to calculate the factorial of a number.
3. Write a function that outputs the Fibonacci series for a given number.
4. Write a program to sort a list of integers.
5. Write a function to find the second largest number in a list.
6. Write a program to swap two variables.
7. Write a function to check whether a given number is a prime number.
8. Write a program to add two matrices.
9. Write a function to find the longest consecutive repeating character in a string.
10. Write a program for a linear search or binary search.
11. Write a function to add 'n' number of sequences.
12. Write a program to compute Euclidean Distance.
13. Write a function that sorts a dictionary by its value.
14. Write a function that counts the number of occurrences of a specific item in a list.
15. Write a function to remove duplicates from a list.
16. Write a function to check whether a string is a palindrome or not.
17. Write a program to check if a number is Armstrong or not.
18. Write a function to convert a list into a nested dictionary.
19. Write a program to print out all of the permutations of a string.
20. Write a function to calculate the area of a circle.
21. Implement a queue using stacks in Python.
22. Write a function to count the number of sub-strings in a specific string.
23. Write a program to generate random numbers in Python.
24. Write a function to check whether a number is in a given range.
25. Write a program to print the pattern 'G'.
26. Write a program to count the number of each vowel in a string.
27. Write a Python program to convert seconds into hours, minutes, and seconds.
28. Write a Python program to find all numbers divisible by 6 but not a multiple of 9 in a certain range.
29. Write a Python program to validate if a string is a valid password or not.
30. Write a program using recursion to find the sum of a list.
31. Write a Python program to find the maximum and minimum value of a given flattened list.
32. Write a Python program to compress and decompress string (use zlib).
33. Write a program to find the set difference of two arrays.
34. Write a Python program to calculate the harmonic sum of 'n' numbers.
35. Write a Python function to implement a binary search on a sorted list.
36. Write a Python program to find three numbers from an array such that the sum of three numbers equal to
zero.
37. Write a Python program to concatenate following dictionaries to create a new one.
38. Write a Python function that takes a sequence of numbers and determines if all the numbers are different
from each other.
39. Write a Python program to convert a list of characters into a string.
40. Write a Python program to check if a given number is a perfect square.
41. Write a Python program to print a dictionary line by line.
42. Write a Python function to find the maximum and minimum numbers from a sequence of numbers.
43. Write a Python program to validate an IP Address.
44. Write a Python program to convert an integer to Binary, Octal and Hexadecimal numbers.
45. Write a Python program to find the median among three given numbers.
46. Create a Python function to check if a given key already exists in a dictionary.
47. Write a Python function to find the highest 3 values in a dictionary.
48. Write a Python function to generate all permutations of a list.
49. Write a Python function to multiply all the numbers in a list.
50. Write a Python program to find common items from two lists.
51. Write a Python program to find valid email addresses from a list.
52. Write a Python program to implement your own myfilter() function which works exactly like Python's
built-in function filter().
53. Write a Python function to insert a string in the middle of a string.
54. Write a Python program to calculate the date six months from the current date using the datetime
module.
55. Write a Python function to get a string made of its first three characters of a specified string.
56. Write a Python program to add leading zeroes to a string.
57. Write a Python function to get a string made of 4 copies of the last two characters of a specified string.
58. Write a Python script to concatenate following dictionaries to create a new one.
59. Write a Python program to check whether a given string is number or not using Lambda.
60. Write a Python program to create a lambda function that adds 25 to a given number.
61. Write a Python program to solve the quadratic equation ax**2 + bx + c = 0.
62. Write a Python script to add a key to a dictionary.
63. Write a Python script to check if a given key already exists in a dictionary.
64. Write a Python program to sum all the items in a list.
65. Write a Python program to create a list by concatenating a given list which ranges go from 1 to n.
66. Write a Python program to find the second smallest number in a list.
67. Write a Python program to find the index of an item in a specified list.
68. Write a Python program to flatten a shallow list.
69. Write a Python program to append a list to the second list.
70. Write a Python program to select an item randomly from a list.
71. Write a program to compute the sum of two matrix.
72. Write a program to check the symmetric in a Matrix.
73. Implement a function in Python for the product of two matrices.
74. Write a Python program for binary search in descending order.
75. Write a Python program to implement power function.
76. Write a Python program to determine whether variable is defined or not.
77. Write a Python program to empty a variable without destroying it.
78. Write a Python program to test if a variable is a list or tuple or a set.
79. Write a Python program to get the ASCII value of a character.
80. Write a Python program to return the binary of an input number.
81. Write a Python program to find the roots of a quadratic function.
82. Implement Python swap case function using map() and lambda.
83. Write a Python script to merge two Python dictionaries.
84. Write a Python program to find validity of a string of parentheses, '(', ')', '{', '}', '[' and ']'.
85. Write a Python program to remove spaces from dictionary keys.
86. Write a Python program to get the top three items in a dictionary.
87. Write a Python program to find the highest 3 values in a dictionary.
88. Write a Python program to combine values in python list of dictionaries.
89. Write a Python program to create a dictionary from a string.
90. Write a Python program to sum all the items in a dictionary.
91. Implement Python shift cipher (Caesar cipher).
92. Write a program to imitate switch case in Python.
93. Write a Python function to print diamonds pattern.
94. Write a Python function to find pair with given sum in the list.
95. Write a Python function to find shortest word in a given string.
96. Write a Python function to create all possible combinations from the digits of a given string.
97. Create a Python function that parses a binary file.
98. Write a Python program to make a chain of function decorators (bold, italic, underline etc.).
99. Write a python program creating Magic Square.
100.Write a Python program to find the numbers of a given string and store them in a list.

LIST

1. Write a Python program to calculate the length of a string.


2. Write a Python program to get a single string from two given strings, separated by a space and swap the
first two characters of each string.
3. Write a Python program to add 'ing' at the end of a given string (length should be at least 3). If the given
string already ends with 'ing' then add 'ly' instead.
4. Write a Python function that takes a list of words and returns the length of the longest one.
5. Write a Python program to remove the characters which have odd index values of a given string.
6. Write a Python program to count the occurrences of each word in a given sentence.
7. Write a Python function to convert a given string to all uppercase if it contains at least 2 uppercase
characters in the first 4 characters.
8. Write a Python program to count and display the vowels of a given text.
9. Write a Python program to reverse words in a string.
10. Write a Python program to strip a set of characters from a string.
11. Write a Python program to count repeated characters in a string.
12. Write a Python program to print the index of the character in a string.
13. Write a Python program to check if a string contains all letters of the alphabet.
14. Write a Python program to convert a given string into a list of words.
15. Write a Python program to lowercase first n characters in a string.
16. Write a Python program to swap comma and dot in a string.
17. Write a Python program to count the number of digits & letters in a string.
18. Write a Python program to strip a set of characters from a string.
19. Write a Python program to uppercase first n characters in a string.
20. Write a Python program to validate an IP address.
21. Write a Python program to split a string on the last occurrence of the delimiter.
22. Write a Python program to find the first non-repeating character in a string.
23. Write a Python program to check a string represent an integer or not.
24. Write a Python program to print all permutations of a given string.
25. Write a Python function to insert a string in the middle of a string.
26. Write a Python function to get a string made of the first 2 and the last 2 chars from a given a string.
27. Write a Python function to get a string made of its first three characters of a specified string.
28. Write a Python function to create a string containing all characters in a list.
29. Write a Python function to remove all instances of a given character from a string.
30. Write a Python function to check whether a string is a palindrome or not.
31. Write a Python function to count how many times a character appears in a string.
32. Write a Python function that reverses a string.
33. Write a Python function to convert a string into a list of words.
34. Write a Python function to convert a string in snake_case into camelCase.
35. Write a Python function to sort the words in a string alphabetically.
36. Write a Python function to check if a string contains only whitespace.
37. Write a Python function to check if a string is a valid identifier according to Python's rules.
38. Write a Python function to replace multiple characters in a string.
39. Write a Python function to split a string at uppercase letters.
40. Write a Python program to convert string into date object (mm/dd/yyyy).
41. Write a Python program to extract year, month, date and time using Lambda.
42. Write a Python program to check whether a string starts with specified characters.
43. Write a Python program to create a Caesar encryption
44. Write a Python program to display formatted text (width=50) as output.
45. Write a Python program to remove existing indentation from all of the lines in a given text.
46. Write a Python program to add a prefix text to all of the lines in a string.
47. Write a Python program to set the indentation of the first line.
48. Write a Python program to print the following floating numbers upto 2 decimal places with a sign.
49. Write a Python program to print the following integers with '*' on the right of specified width.
50. Write a Python program to print the following integers with zeros on the left of specified width.
51. Write a Python program to print the following floating numbers with no decimal places.
52. Write a Python program to print the following floating numbers upto 2 decimal places.
53. Write a Python program to print the following floating numbers with a sign.
54. Write a Python program to print the following integers with '*' on the right of specified width.
55. Write a Python program to display a number with a comma separator.
56. Write a Python program to format a number with a percentage.
57. Write a Python program to display a number in left, right and center aligned of width 10.
58. Write a Python program to count occurrences of a substring in a string.
59. Write a Python program to reverse a string.
60. Write a Python program to reverse words in a string.
61. Write a Python program to strip a set of characters from a string.
62. Write a Python program to count repeated characters in a string.
63. Write a Python program to print the index of the character in a string.
64. Write a Python program to check if a string contains all letters of the alphabet.
65. Write a Python program to convert a string in a list.
66. Write a Python program to lowercase first n characters in a string.
67. Write a Python program to swap comma and dot in a string.
68. Write a Python program to count the number of digits in a string.
69. Write a Python program to search the numbers (0-9) of length between 1 to 3 in a given string.
70. Write a Python program to match a string that contains only upper and lowercase letters, numbers, and
underscores.
71. Write a Python program where a string will start with a specific number.
72. Write a Python program to remove leading zeros from an IP address.
73. Write a Python program to check for a number at the end of a string.
74. Write a Python program to search some literals strings in a string.
75. Write a Python program to search a literals string in a string and also find the location within the original
string where the pattern occurs.
76. Write a Python program to abbreviate 'Road' as 'Rd.' in a given string.
77. Write a Python program to replace all occurrences of space, comma, or dot with a colon.
78. Write a Python program to swap commas and dots in a string.
79. Write a Python program to remove whitespaces from a string.
80. Write a Python program to remove everything except alphanumeric characters from a string.
81. Write a Python program to find urls in a string.
82. Write a Python program to split a string at uppercase letters.
83. Write a Python program to do a case-insensitive string replacement.
84. Write a Python program to remove the parenthesis area in a string.
85. Write a Python program to insert spaces between words starting with capital letters.
86. Write a Python program to reverse words in a string.
87. Write a Python program to print letters from the English alphabet from a-z and A-Z.
88. Write a Python program to generate and print a list and a dictionary of square of numbers between 1 and
15 (both included).
89. Write a Python program to print without newline or space.
90. Write a Python program to detect the number of local variables declared in a function.
91. Write a Python program to print letters from the English alphabet A-Z (uppercase).
92. Write a Python program to print letters from the English alphabet a-z (lowercase).
93. Write a Python program to print only the words with odd number of characters in a string.
94. Write a Python program to replace all occurrences of a given character with another character in a string.
95. Write a Python program to split a string on the last occurrence of the delimiter.
96. Write a Python program to find the first non-repeating character in given string.
97. Write a Python program to check if a string represents an integer or not.
98. Write a Python program to remove duplicate words in a string.
99. Write a Python program to convert snake case string to camel case string.

TUPLE

1. Write a Python program to create and display a tuple.


2. Write a Python program to create a tuple with different data types.
3. How can you convert a tuple into a list?
4. Write a Python program to get the 4th element from the start and 4th element from the end of a tuple.
5. Write a Python program to find the repeated items of a tuple.
6. Write a Python program to check whether an element exists within a tuple.
7. Write a Python program to convert a list to a tuple.
8. Write a Python program to remove an item from a tuple.
9. Write a Python program to slice a tuple.
10. Write a Python program to find the index of an item of a tuple.
11. Write a Python program to find the length of a tuple.
12. Write a Python program to convert a tuple to a dictionary.
13. Write a Python program to unzip a list of tuples into individual lists.
14. Write a Python program to reverse a tuple.
15. Write a Python program to convert a list of tuples into a dictionary.
16. Write a Python program to print a tuple with a string formatting.
17. Write a Python program to replace the last value of tuples in a list.
18. Write a Python program to sort a tuple by its float element.
19. Write a Python program to count the elements in a tuple until an element is a specific character.
20. Write a Python program to compute element-wise sum of given tuples.
21. Write a Python program to sort tuples by their maximum element.
22. Write a Python program to replace element of a tuple with a specified element.
23. Write a Python program to flatten a list of tuples.
24. Write a Python program to convert a tuple to a float.
25. Write a Python program to convert a tuple to an integer.
26. Write a Python program to check if all items of a tuple are the same.
27. Write a Python program to access and print a specific character in a tuple.
28. Write a Python program to compute total of all the elements of a given tuple.
29. Write a Python program to create a nested tuple.
30. Write a Python program to unpack a given tuple to a dictionary.
31. Write a Python program to create a sorted list of tuples from a dictionary.
32. Write a Python program to create a tuple from a string.
33. Write a Python program to create a tuple from a list of integers.
34. Write a Python program to create a tuple of mixed data types.
35. Write a Python program to append an item to a tuple.
36. Write a Python program to convert a specified element to a tuple, list and set.
37. Write a Python program to join two tuples in a specific way.
38. Write a Python program to convert a list into a tuple after checking if all elements of the list are numbers.
39. Write a Python program to convert a tuple to a string.
40. Write a Python program to get the maximum and minimum value in a dictionary.
41. Write a Python program to concatenate tuples to form a dictionary.
42. Write a Python program to convert two tuples into a dictionary.
43. Write a Python program to convert a tuple to an array.
44. Write a Python program to convert a tuple to a set.
45. Write a Python program to create a nested tuple containing a dictionary.
46. Write a Python program to convert a list of tuples into a tuple.
47. Write a Python program to concatenate two tuples.
48. Write a Python program to duplicate all items of a tuple.
49. Write a Python program to duplicate all items of a list wrapped in a tuple.
50. Write a Python program to calculate the average value of the numbers in a given tuple of tuples.
51. Write a Python program to convert a given tuple into dictionary.
52. Write a Python program to print a tuple where the string elements will be uppercase.
53. Write a Python program to combine two dictionary adding values for common keys.
54. Write a Python program to replace first item of a tuple in a list.
55. Write a Python program to sort a list of nested tuples.
56. Write a Python program to replace last element in a list with another list.
57. Write a Python program to remove an empty tuple from a list of tuples.
58. Write a Python program to sort a tuple by its string length.
59. Write a Python program to convert a tuple typewise into a list.
60. Write a Python program to reverse the elements of a given tuple.
61. Write a Python program to convert an integer tuple to a float tuple.
62. Write a Python program to convert a specified list to a tuple.
63. Write a Python program to convert a specified list to a tuple float.
64. Write a Python program to get unique values from a specified tuple.
65. Write a Python program to concatenate two or more tuples.
66. Write a Python program to calculate the average value of the numbers in a given tuple.
67. Write a Python program to check if a specified element presents in a tuple of tuples.
68. Write a Python program to compute the largest number of all numeric items in a tuple.
69. Write a Python program to compute the smallest number of all numeric items in a tuple.
70. Write a Python program to generate a list that contains the tuples (number, square).
71. Write a Python program to find two repeated items in a given tuple.
72. Write a Python program to check if a specified element presents in a tuple or in a list.
73. Write a Python program to convert a float number to integer.
74. Write a Python program to convert a string to a float number.
75. Write a Python program to convert a string to an integer.
76. Write a Python program to convert an integer to a string.
77. Write a Python program to convert an integer to a float number.
78. Write a Python program to convert two tuples into a dictionary.
79. Write a Python program to convert a tuple of characters into a string.
80. Write a Python program to slice a tuple.
81. Write a Python program to create the colon of a tuple.
82. Write a Python program to find maximum and the minimum value in a set.
83. Write a Python program to check if a item exists in a tuple.
84. Write a Python program to convert a list to a tuple.
85. Write a Python program to remove an item from a tuple.
86. Write a Python program to slice a tuple.
87. Write a Python program to find the index of an item of a tuple.
88. Write a Python program to find the length of a tuple.
89. Write a Python program to convert a tuple to a dictionary.
90. Write a Python program to unzip a list of tuples into individual lists.
91. Write a Python program to reverse a tuple.
92. Write a Python program to convert a list of tuples into a dictionary.
93. Write a Python program to print a tuple with string formatting.
94. Write a Python program to replace the last value of tuples in a list.
95. Write a Python program to sort a tuple by its float element.
96. Write a Python program to count the elements in a tuple until an element is a specific character.
97. Write a Python program to compute element-wise sum of given tuples.
98. Write a Python program to sort tuples by their maximum element.
99. Write a Python program to replace element of a tuple with a specified element.
100.Write a Python program to flatten a list of tuples.

SET

1. Write a Python program to create a set.


2. Write a Python program to iterate over sets.
3. Write a Python program to add member(s) in a set.
4. Write a Python program to remove item(s) from set.
5. Write a Python program to remove an item from a set if it is present in the set.
6. Write a Python program to create an intersection of sets.
7. Write a Python program to create a union of sets.
8. Write a Python program to create the difference of two or more sets.
9. Write a Python program to create a symmetric difference of sets.
10. Write a Python program to check if a set is a subset of another set.
11. Write a Python program to check if a set is a superset of another set.
12. Write a Python program to check if a set is disjoint with another set.
13. Write a Python program to find maximum and minimum values of a set.
14. Write a Python program to find the length of a set.
15. Write a Python program to check if an element exists in a set.
16. Write a Python program to convert a list into a set.
17. Write a Python program to convert a tuple into a set.
18. Write a Python program to convert a string into a set.
19. Write a Python program to create a shallow copy of sets.
20. Write a Python program to create a deep copy of sets.
21. Write a Python program to use of frozensets (use cases).
22. Write a Python program to clear a set.
23. Write a Python program to use a set if a set is less than another set.
24. Write a Python program to remove the intersection of a second set from the first set.
25. Write a Python program to use a set if a set is less than or equal to another set.
26. Write a Python program to use a set if a set is greater than another set.
27. Write a Python program to use a set if a set is greater than or equal to another set.
28. Write a Python program to create set difference.
29. Write a Python program to create a symmetric difference update.
30. Write a Python program to use of hashable sets.
31. Write a Python program to compare two sets.
32. Write a Python program to create a positive single integer value from specified values.
33. Write a Python program to create a positive single integer value from the unique specified values
of the said tuple.
34. Write a Python program to find a missing numbers from a list.
35. Write a Python program to compute average of two sets.
36. Write a Python program to find common element(s) in two sets.
37. Write a Python program to find uncommon elements from two given sets.
38. Write a Python program to combine several given lists into a list of lists.
39. Write a Python program to create a list with infinite elements.
40. Write a Python program to convert a list of characters into a string.
41. Write a Python program to find common element(s) in three given lists.
42. Write a Python program to convert list of lists into a list of sets.
43. Write a Python program to find missing and additional values in two lists.
44. Write a Python program to compute the similarity between two lists.
45. Write a Python program to create a dictionary from two lists without losing duplicate values.
46. Write a Python program to create an intersection of sets from the provided lists.
47. Write a Python program to create a union of sets from the provided lists.
48. Write a Python program to find majority elements in the provided list.
49. Write a Python program to get unique combinations of elements from a given list.
50. Write a Python program to get all disallowed combinations of elements of the provided list.
51. Write a Python program to find perfect squares between two given numbers.
52. Write a Python program to compute the sum of all elements in the provided set.
53. Write a Python program to find the duplicate elements in the given set.
54. Write a Python program to find elements that are in one set, but not in others.
55. Write a Python program to convert a nested tuple to a flattened tuple.
56. Write a Python program to compute element-wise product of two sets.
57. Write a Python program to compute element-wise sum of two sets.
58. Write a Python program to get unique tuples from a list of tuples.
59. Write a Python program to find common tuples between two given lists.
60. Write a Python program to find all duplicate subsets from a given list of subsets.
61. Write a Python program to convert a list of characters into a set.
62. Write a Python program to check if a particular element is present in the given set or not.
63. Write a Python program to find elements in one set which are not in others.
64. Write a Python program to convert a list of integers into a set.
65. Write a Python program to check if a given set is disjoint with another set.
66. Write a Python program to remove an element from a set if it is present.
67. Write a Python program to filter the elements of the given set based on a function.
68. Write a Python program to check if a tuple exists in a set of tuples.
69. Write a Python program to get the elements of a set that are not in another set.
70. Write a Python program to find the elements that are in one set but not the other (set
difference).
71. Write a Python program to sort a set of strings.
72. Write a Python program to convert a list of characters into a set.
73. Write a Python program to remove multiple elements from a set.
74. Write a Python program to get the powerset of a set.
75. Write a Python program to check if two sets are disjoint.
76. Write a Python program to check if a set is a subset of another set.
77. Write a Python program to keep only unique elements of a set.
78. Write a Python program to get the intersection of multiple given sets.
79. Write a Python program to get the union of multiple given sets.
80. Write a Python program to get the symmetric difference between two given sets.
81. Write a Python program to remove duplicate elements from a set.
82. Write a Python program to get the frequency of the elements in a set.
83. Write a Python program to find all the elements in a set which are also present in another set.
84. Write a Python program to add elements to a set.
85. Write a Python program to delete elements from a set.
86. Write a Python program to copy a set.
87. Write a Python program to find elements of set A which are not present in set B (A - B).
88. Write a Python program to convert a set of tuples into a tuple of sets.
89. Write a Python program to create a set from a string.
90. Write a Python program to find the index of a element in a set.
91. Write a Python program to replace an element in a set.
92. Write a Python program to add two sets.
93. Write a Python program to remove all elements from a set.
94. Write a Python program to check if a set is empty.
95. Write a Python program to count occurrences of set elements.
96. Write a Python program to get the set of all elements in either set, but not both (set symmetric
difference).
97. Write a Python program to check if a set is a superset of all other sets.
98. Write a Python program to add an element to the set at a specific index.
99. Write a Python program to create a sorted set of numbers.
100.Write a Python program to update a set.

DICT

101.Write a Python script to sort (ascending and descending) a dictionary by value.


102.Write a Python script to add a key to a dictionary.
103.Write a Python script to concatenate following dictionaries to create a new one.
104.Write a Python script to check whether a given key already exists in a dictionary.
105.Write a Python program to iterate over dictionaries using for loops.
106.Write a Python script to generate and print a dictionary that contains a number (between 1 and
n) in the form (x, x*x).
107.Write a Python script to print a dictionary where the keys are numbers between 1 and 15 (both
included) and the values are square of keys.
108.Write a Python script to merge two Python dictionaries.
109.Write a Python program to iterate over dictionaries using for loops.
110.Write a Python program to sum all the items in a dictionary.
111.Write a Python program to multiply all the items in a dictionary.
112.Write a Python program to remove a key from a dictionary.
113.Write a Python program to map two lists into a dictionary.
114.Write a Python program to sort a dictionary by key.
115.Write a Python program to get the maximum and minimum value in a dictionary.
116.Write a Python program to get a dictionary from an object's fields.
117.Write a Python program to remove duplicates from Dictionary.
118.Write a Python program to check a dictionary is empty or not.
119.Write a Python program to combine two dictionary adding values for common keys.
120.Write a Python program to print all unique values in a dictionary.
121.Write a Python program to create and display all combinations of letters, selecting each letter
from a different key in a dictionary.
122.Write a Python program to find the highest 3 values in a dictionary.
123.Write a Python program to combine values in python list of dictionaries.
124.Write a Python program to create a dictionary from a string.
125.Write a Python program to print a dictionary in table format.
126.Write a Python program to count the values associated with key in a dictionary.
127.Write a Python program to sort Counter by value.
128.Write a Python program to create a dictionary from two lists without losing duplicate values.
129.Write a Python program to replace dictionary values with their average.
130.Write a Python program to match key values in two dictionaries.
131.Write a Python program to store a given dictionary in a json file.
132.Write a Python program to create a dictionary of keys x, y, and z where each key has as value a
list from 11-20, 21-30, 31-40 respectively.
133.Write a Python program to get the key, value and item in a dictionary.
134.Write a Python program to print a dictionary line by line.
135.Write a Python program to check multiple keys exist in a dictionary.
136.Write a Python program to count number of items in a dictionary value that is a list.
137.Write a Python program to sort a list alphabetically in a dictionary.
138.Write a Python program to create a dictionary from a string.
139.Write a Python program to print a dictionary line by line.
140.Write a Python program to check whether a dictionary contains a specific key.
141.Write a Python script to print a dictionary where the keys are numbers between 1 and 15 and the
values are their squares.
142.Write a Python script to merge two Python dictionaries.
143.Write a Python script to add a key to a dictionary.
144.Write a Python script to concatenate following dictionaries to create a new one.
145.Write a Python script to sort (ascending and descending) a dictionary by value.
146.Write a Python script to check if a given key already exists in a dictionary.
147.Write a Python script to generate a dictionary that contains numbers in the form (x, x*x)
between 1 and n.
148.Write a Python script to create a dictionary from a string.
149.Write a Python program to iterate over dictionaries using for loops.
150.Write a Python script to generate and print a dictionary that contains a number (between 1 and
n) in the form (x, x*x).
151.Write a Python script to filter a dictionary based on values.
152.Write a Python program to drop empty Items from a given Dictionary.
153.Write a Python program to filter a dictionary based on keys.
154.Write a Python program to get the top three items in a shop.
155.Write a Python program to get the priority of a value in a given dictionary.
156.Write a Python program to get a list, sorted in increasing order by the last element in each tuple
from a given list of non-empty tuples.
157.Write a Python program to count all values associated with a specific key in a dictionary.
158.Write a Python program to sort Counter by key.
159.Write a Python program to create a dictionary from a string.
160.Write a Python program to print a dictionary line by line.
161.Write a Python program to check multiple keys exist in a dictionary.
162.Write a Python program to count the frequency of values in a dictionary.
163.Write a Python program to convert a list into nested dictionaries of keys.
164.Write a Python program to sort a dictionary by key.
165.Write a Python program to get the maximum and minimum value in a dictionary.
166.Write a Python program to get a dictionary from an object fields.
167.Write a Python program to remove duplicates values from Dictionary.
168.Write a Python program to check a dictionary is empty or not.
169.Write a Python program to combine two dictionaries adding values for common keys.
170.Write a Python program to check whether an element exists within a dictionary.
171.Write a Python program to find the highest three values in a dictionary.
172.Write a Python program which sums up dict values.
173.Write a Python program to convert dictionary into list of tuples.
174.Write a Python program to create a dictionary from two lists.
175.Write a Python program to make a dictionary from a string.
176.Write a Python program to check if a dictionary is a subset of another large dictionary.
177.Write a Python program to get a dictionary from an object's fields.
178.Write a Python program to remove duplicates from Dictionary.
179.Write a Python program to check a dictionary is empty or not.
180.Write a Python program that takes a dictionary as input and returns a list of all the unique values.
181.Write a Python program to combine two dictionary adding values for common keys.
182.Write a Python program to print all unique values in a dictionary.
183.Write a Python program to create a dictionary of keys x, y, and z where each key has as value a
list from 11-20, 21-30, 31-40.
184.Write a Python program to get the key, value and item in a dictionary.
185.Write a Python program to print a dictionary line by line.
186.Write a Python program to check multiple keys exist in a dictionary.
187.Write a Python program to count number of items in a dictionary value that is a list.
188.Write a Python program to count the number occurrences of a particular value in a given
dictionary.
189.Write a Python program to replace all occurrences of a particular value from a given dictionary.
190.Write a Python program to find the length of a given dictionary.
191.Write a Python program to sort a dictionary based on its keys.
192.Write a Python program to sort a dictionary based on its values.
193.Write a Python program to copy a dictionary.
194.Write a Python program to clear all items in a dictionary.
195.Write a Python program to get a dictionary from an object's fields.
196.Write a Python program to remove duplicates from Dictionary.
197.Write a Python program to check if a dictionary is a subset of another dictionary.
198.Write a Python program to convert list of tuples into a dictionary.
199.Write a Python program to check whether a given dictionary is empty or not.
200.Write a Python program to combine two dictionary adding values for common keys.

COMBINE ALL TOPICS

201.Write a Python program that converts a list into a nested dictionary.


202.Write a Python function that accepts two tuples and returns a set consisting of all the unique
elements from both the tuples.
203.Write a Python script that converts a dictionary where each key has a list of values into a list of
dictionaries.
204.Write a Python program that converts a set of tuples into a dictionary.
205.Write a Python program to combine two lists into a dictionary, where elements of the first list
are the keys, and elements of the second list are the values.
206.Write a Python program that generates a list of tuples from a given set.
207.Write a Python program that converts a tuple of integers into a list of strings.
208.Write a Python function that finds the common elements between a list, a set, and a tuple.
209.Write a Python function that presents a dictionary where the keys are elements from a given list,
and the values are the frequencies of these elements in a given tuple.
210.Write a Python function to create a list from a given set of tuples.
211.Write a Python program that accepts a list of numbers and creates a dictionary with a number as
a key, and it's square as value.
212.Write a Python program that transforms two lists into a list of tuples.
213.Write a Python function that interchanges the keys and values in a dictionary. The values are
given as sets.
214.Write a Python program that transforms a list of strings into a tuple of dictionaries. Each
dictionary consists of a string and its length from the given list.
215.Write a Python program that converts a dictionary of lists into a list of dictionaries.
216.Write a Python function that transforms a list into a dictionary of element frequencies.
217.Write a Python function that presents all the unique items in a given dictionary into a set.
218.Write a Python function that converts a list of sets into a set of lists.
219.Write a Python function that reverses the keys and values in a dictionary. The keys are in a tuple
format.
220.Write a Python program to use sets to create a dictionary.
221.Write a Python program to convert two tuples into a dictionary.
222.Write a Python script to turn a list of lists into a set of sets.
223.Write a Python program to create a dictionary pairing corresponding keys from two lists to values
from a third list.
224.Write a Python program to transform a list of characters into a dictionary consisting of keys as
ascii values and character as values.
225.Write a Python program to create a list of values and enumerate it to construct a dictionary
where the elements are the keys and their index are the values.
226.Write a Python script to create a list of unique tuples from a list of tuples.
227.Write a Python function to create a dictionary from a string, but exclude duplicates from keys.
228.Write a Python program to get the top three items in a set of tuples based on the second item of
each tuple.
229.Write a Python program to convert a dictionary to a set of tuples where each tuple consists of a
key-value pair.
230.Write a Python program to make a chain of functions decorators that will transform a dictionary
into a string in a unique format.
231.Write a Python program to convert a list of dictionaries into a dictionary of lists.
232.Write a Python program to convert a dictionary of tuples into a tuple of dictionaries.
233.Create a Python function that takes two sets and returns a list of the items that they have in
common.
234.Write a Python function to create a tuple from multiple data types (list, set, dictionary).
235.Write a Python program to store a dictionary in another dictionary.
236.Create a Python function that takes a list of tuples and turns it into a dictionary.
237.Create a Python function that takes a dictionary and turns it into a tuple of key-value pairs.
238.Write a Python function to convert a list of sets into a set of lists.
239.Write a Python function that presents all the unique values in a dictionary as a set.
240.Write a Python program to convert keys from a dictionary into a tuple.
241.Write a Python program that transforms all the unique values from a dictionary into a set.
242.Use a dictionary to convert a list of integers into a list of equivalent ASCII characters.
243.Create a Python function that retrieves all the values from a dictionary and places them in a
tuple.
244.Write a Python function to convert a list of integers into a set.
245.Create a Python function to convert a list of tuples into a dictionary, where the first item in each
tuple is the key and the second is the value.
246.In Python, write a script to convert a set of tuples into a set of lists.
247.Create a Python function that converts a list of strings into a dictionary where the keys are the
strings and the values are the lengths of the corresponding string.
248.Write a Python program to convert a dictionary into a list of tuples, where each tuple consists of
a key-value pair.
249.Write a Python function to turn a tuple into a nested list.
250.Write a Python program that creates a tuple of all values in a list that are a certain data type (e.g.
string, integer, etc.).
251.Write a Python function to store lists in a dictionary.
252.Write a Python function to add new items to a dictionary using a key-value tuple.
253.Create a Python function that extracts the keys from a dictionary and puts them into a list.
254.Write a Python program to transform a set of lists into a tuple of sets.
255.Create a Python function that adds a single value to a specific set inside a dictionary.
256.Write Python code to convert a dictionary into a list of sets, where each set contains a key and its
corresponding value.
257.Write a Python function that compares the key-value pairs in a dictionary with tuples in a list.
258.Write a Python function that transforms a list into a set

--------------------------------------------------------------------------------------------------------------------------------------------------------
SUMMARY OF ALL

REGEX
Symbol/Method Description Input Example Output
Example

\d Matches any digit re.findall(r'\d', 'abc123') ['1', '2', '3']

\D Matches any non-digit character re.findall(r'\D', 'abc123') ['a', 'b', 'c']

\s Matches any whitespace re.findall(r'\s', 'a b c') [' ', ' ']
character

\S Matches any non-whitespace re.findall(r'\S', 'a b c') ['a', 'b', 'c']


character

\w Matches any alphanumeric re.findall(r'\w', '#abc!') ['a', 'b', 'c']


character

\W Matches any non-alphanumeric re.findall(r'\W', '#abc!') ['#', '!']


character

. Matches any character except re.findall(r'.', 'abc') ['a', 'b', 'c']


newline

^ Matches the start of the string bool(re.match(r'^a', 'abc')) True

$ Matches the end of the string bool(re.search(r'c$', 'abc')) True

[abc] Matches any character in the set re.findall(r'[abc]', 'abcdef') ['a', 'b', 'c']

[^abc] Matches any character not in the re.findall(r'[^abc]', 'abcdef') ['d', 'e', 'f']
set

a\u007Cb Matches either 'a' or 'b' `re.findall(r'a b', 'abcdef')`

* Matches 0 or more repetitions re.findall(r'\d*', 'ab123') ['', '', '', '123',


'']

+ Matches 1 or more repetitions re.findall(r'\d+', 'ab123') ['123']

? Matches 0 or 1 character re.findall(r'\d?', 'ab123') ['', '', '', '1',


'2', '3', '']

{n} Matches exactly n repetitions re.findall(r'\d{2}', 'ab123') ['12']

{n,} Matches n or more repetitions re.findall(r'\d{2,}', 'ab123') ['123']

{n,m} Matches between n and m re.findall(r'\d{1,2}', 'ab123') ['12', '3']


repetitions

(...) Defines a group re.match(r'(ab)', 'abc').groups() ('ab',)


Symbol/Method Description Input Example Output
Example

(?P<name>...) Defines a named group re.match(r'(?P<first>ab)', {'first': 'ab'}


'abc').groupdict()

\number Matches the contents of a group re.match(r'(ab)', 'ab'


by number 'abc').group(1)

(?=...) Positive lookahead assertion `re.findall(r'Windows(?=95 98

(?!...) Negative lookahead assertion re.findall(r'\d+(?!%)', '100% 50 ['50']


10%')

(?<=...) Positive lookbehind assertion re.findall(r'(?<=abc)def', ['def']


'abcdef')

(?<!...) Negative lookbehind assertion re.findall(r'(?<!abc)def', ['def']


'abcdef xyzdef')

match() Determines if the regex matches bool(re.match('^h', 'hello')) True


at the beginning

search() Searches the string for a match bool(re.search('ell', 'hello')) True

findall() Returns all matches as a list re.findall('l', 'hello') ['l', 'l']

sub() Replaces one or many matches re.sub('l', 'r', 'hello') 'herro'

re.IGNORECASE / re.I Ignore case re.findall('a', 'abc ABC', re.I) ['a', 'A', 'A']

re.MULTILINE / re.M Multiline matching len(re.findall('^a', 'abc\ndef\ 2


nabc\n', re.M))

re.DOTALL / re.S Make . match newlines as well re.findall('a.b', 'a\nb a b', re.S) ['a\nb', 'a b']
STRING

Method Description Input Example Output


Example

capitalize() Returns the string with its first character 'HELLO'.capitalize() 'Hello'
capitalized and the rest lowercased

lower() Converts all the string's characters to lower 'HELLO'.lower() 'hello'


case

upper() Converts all the string's characters to upper 'hello'.upper() 'HELLO'


case

count(sub[, start[, Returns the number of non-overlapping 'hello'.count('l') 2


end]]) occurrences of substring sub in the string's
slice [start:end]

replace(old, new[, Returns a copy of the string with all 'hello'.replace('l','y') 'heyyo'
count]) occurrences of substring old replaced by new

Method Description Input Example Output


Example

split([sep[, maxsplit]]) Returns a list of words in the string, 'hello world'.split(' ') ['hello',
using sep as the delimiter string 'world']

strip([chars]) Returns a copy of the string with the leading ' hello '.strip() 'hello'
and trailing characters removed

find(sub[, start[, end]]) Returns the lowest index in the string where 'hello'.find('l') 2
substring sub is found, -1 if not found

index(sub[, start[, Like find(), but raises ValueError when the 'hello'.index('l') 2
end]]) substring is not found

startswith(prefix[, Returns True if string starts with the prefix, 'hello'.startswith('h') True
start[, end]]) otherwise returns False

endswith(suffix[, start[, Returns True if string ends with the suffix, 'hello'.endswith('o') True
end]]) otherwise returns False

join(iterable) Returns a string which is the concatenation of '- 'hello -


the strings in the iterable '.join(['hello','world']) world'
TUPLE

Method Description Input Example Output


Example

count() Returns the number of times a specified value occurs in a (1, 2, 2, 3, 4).count(2) 2
tuple

index() Searches the tuple for a specified value and returns the (1, 2, 2, 3, 4).index(2) 1
position of where it was found

TUPLE

Operation / Function Description Input Example Output Example

Slicing [a:b] Fetches the elements from index 'a' (1, 2, 3, 4, 5)[1:3] (2, 3)
to 'b-1'

Concatenation + Combines tuples (1, 2, 3) + (4, 5) (1, 2, 3, 4, 5)

Repetition * Repeats a tuple (1, 2, 3) * 2 (1, 2, 3, 1, 2, 3)

Membership in Check if an item exists in the tuple 1 in (1, 2, 3) True

Looping Iterating through a tuple [x for x in (1, 2, 3)] [1, 2, 3]

len() Returns the number of elements in a len((1, 2, 3)) 3


tuple

Unpacking * Unpacking the elements of a tuple a, *b, c = (1, 2, 3, [2, 3]


4) then print(b)
LIST

Method Description Input Example Output


Example

append() Adds an element at the end of the list ['a', 'b'].append('c') ['a', 'b', 'c']

clear() Removes all the elements from the list ['a', 'b'].clear() []

copy() Returns a copy of the list ['a', 'b'].copy() ['a', 'b']

count() Returns the number of elements with the specified ['a', 'b', 'a'].count('a') 2
value

extend() Add the elements of a list (or any iterable), to the ['a', 'b'].extend(['c', 'd']) ['a', 'b', 'c', 'd']
end of the current list

index() Returns the index of the first element with the ['a', 'b', 'a'].index('b') 1
specified value

insert() Adds an element at the specified position ['a', 'b'].insert(1, 'c') ['a', 'c', 'b']

pop() Removes the element at the specified position ['a', 'b', 'c'].pop(1) 'b'

remove() Removes the first item with the specified value ['a', 'b', 'a'].remove('a') ['b', 'a']

reverse() Reverses the order of the list ['a', 'b', 'c'].reverse() ['c', 'b', 'a']

sort() Sorts the list [3, 2, 1].sort() [1, 2, 3]


DICT

Method Description Input Example Output Example

clear() Removes all elements from the {'a': 1, 'b': 2}.clear() {}


dictionary

copy() Returns a copy of the dictionary {'a': 1, 'b': 2}.copy() {'a': 1, 'b': 2}

fromkeys(seq[, v]) Returns a new dictionary with keys from dict.fromkeys(['a', {'a': 1, 'b': 1}
seq and value equal to v 'b'], 1)

get(key[,d]) Returns the value of the key. If the key {'a': 1, 'b': 2}.get('a') 1
does not exist, return d (defaults to
None)

items() Returns a new object of the dictionary's {'a': 1, 'b': 2}.items() dict_items([('a', 1),
items in (key, value) format ('b', 2)])

keys() Returns a new object of the dictionary's {'a': 1, 'b': 2}.keys() dict_keys(['a', 'b'])
keys

pop(key[,d]) Removes the item with the key and {'a': 1, 'b': 2}.pop('a') 1
returns its value or d if key is not found.
If d is not provided and key is not found,
it raises KeyError

popitem() Removes and returns a (key, value) pair {'a': 1, 'b': ('b', 2)
as a 2-tuple 2}.popitem()

setdefault(key[,d]) Returns the value of key. If key does not {'a': 1, 'b': 3
exist, insert key with a value of d and 2}.setdefault('c', 3)
return d (defaults to None)

update([other]) Updates the dictionary with the {'a': 1, 'b': {'a': 1, 'b': 3}
key/value pairs from other, overwriting 2}.update({'b':3})
existing keys

values() Returns a new object of the dictionary's {'a': 1, 'b': 2}.values() dict_values([1, 2])
values
SET

Method Description Input Example Output


Example

add() Adds an element example = set(); example.add(1); {1}


to the set print(example)

clear() Removes all example = {1,2}; example.clear(); set()


elements from the print(example)
set

copy() Returns a copy of example = {1,2}; print(example.copy()) {1,2}


the set

difference() Returns the print({1,2}.difference({2,3})) {1}


difference of two
or more sets as a
new set

difference_update() Removes all example = {1,2}; {1}


elements of example.difference_update({2,3});
another set from print(example)
this set

discard() Removes an example = {1,2}; example.discard(2); {1}


element from the print(example)
set if it is a
member. (Do
nothing if the
element is not in
set)

intersection() Returns the print({1,2}.intersection({2,3})) {2}


intersection of
two sets as a new
set

intersection_update() Updates the set example = {1,2}; {2}


with the example.intersection_update({2,3});
intersection of print(example)
itself and another

isdisjoint() Returns True if print({1,2}.isdisjoint({2,3})) False


two sets have a
null intersection

issubset() Returns True if print({1,2}.issubset({1,2,3})) True


another set
contains this set

issuperset() Returns True if print({1,2}.issuperset({1,2,3})) False


this set contains
another set
Method Description Input Example Output
Example

pop() Removes and example = {1,2}; print(example.pop()) 1 (or 2,


returns an it's
arbitrary set arbitrary)
element.
Raises KeyError if
the set is empty

remove() Removes an example = {1,2}; example.remove(2); {1}


element from the print(example)
set. If the element
is not a member,
raises a KeyError

symmetric_difference() Returns the print({1,2}.symmetric_difference({2,3})) {1, 3}


symmetric
difference of two
sets as a new set

symmetric_difference_update() Updates a set with example = {1,2}; {1, 3}


the symmetric example.symmetric_difference_update({2,3});
difference of itself print(example)
and another

union() Returns the union print({1,2}.union({2,3})) {1, 2, 3}


of sets in a new
set

update() Updates the set example = {1,2}; example.update({2,3}); {1, 2, 3}


with the union of print(example)
itself and others
String:
Method Description

capitalize() Converts the first character to upper case

casefold() Converts string into lower case

center() Returns a centered string

count() Returns the number of times a specified value occurs in a string

encode() Returns an encoded version of the string

endswith() Returns true if the string ends with the specified value

expandtabs() Sets the tab size of the string

find() Searches the string for a specified value and returns the position of where it was found

format() Formats specified values in a string

index() Searches the string for a specified value and returns the position of where it was found

isalnum() Returns True if all characters in the string are alphanumeric

isalpha() Returns True if all characters in the string are in the alphabet

isdigit() Returns True if all characters in the string are digits

islower() Returns True if all characters in the string are lower case

isspace() Returns True if all characters in the string are whitespaces

istitle() Returns True if the string follows the rules of a title

isupper() Returns True if all characters in the string are upper case

join() Joins the elements of an iterable to the end of the string

lstrip() Returns a left trim version of the string

replace() Returns a string where a specified value is replaced with a specified value

split() Splits the string at the specified separator and returns a list

strip() Returns a trimmed version of the string


List:
Method Description

append() Adds an element at the end of the list

clear() Removes all the elements from the list

copy() Returns a copy of the list

count() Returns the number of elements with the specified value

extend() Add the elements of a list (or any iterable), to the end of the current list

index() Returns the index of the first element with the specified value

insert() Adds an element at the specified position

pop() Removes the element at the specified position

remove() Removes the item with the specified value

reverse() Reverses the order of the list

sort() Sorts the list


Set:
Method Description

add() Adds an element to the set

clear() Removes all the elements from the set

copy() Returns a copy of the set

difference() Returns a set containing the difference between two or more sets

difference_update() Removes the items in this set that are also included in another, specified
set

discard() Remove the specified item

intersection() Returns a set, that is the intersection of two other sets

intersection_update() Removes the items in this set that are not present in other, specified
set(s)

isdisjoint() Returns whether two sets have a intersection or not

issubset() Returns whether another set contains this set or not

issuperset() Returns whether this set contains another set or not

pop() Removes an element from the set

remove() Removes the specified element from the set

symmetric_difference() Returns a set with the symmetric differences of two sets

symmetric_difference_update() Inserts the symmetric differences from this set and another
union() Return a set containing the union of sets

update() Update the set with another set, or any other iterable
Tuple:
Method Description

count() Returns the number of times a specified value occurs in a tuple

index() Searches the tuple for a specified value and returns the position of where it was found
Dictionary:
Method Description

clear() Removes all the elements from the dictionary

copy() Returns a copy of the dictionary

fromkeys() Returns a dictionary with the specified keys and values

get() Returns the value of the specified key

items() Returns a list containing the dictionary's key-value tuple pairs

keys() Returns a list containing the dictionary's keys

pop() Removes the element with the specified key

popitem() Removes the last inserted key-value pair

setdefault() Returns the value of the specified key. If the key does not exist: insert the key, with the specified
value

update() Updates the dictionary with the specified key-value pairs

values() Returns a list of all the values in the dictionary


Method List Set Tuple Dictionary String

append() list.append('c') N/A N/A N/A N/A

remove() list.remove('a') set.remove('a') N/A N/A N/A

add() N/A set.add('c') N/A N/A N/A

discard() N/A set.discard('a') N/A N/A N/A

sort() list.sort() set.sorted() N/A N/A N/A

index() list.index('b') N/A tuple.index('b') N/A str.index('b')

count() list.count('a') N/A tuple.count('a') N/A str.count('a')

keys() N/A N/A N/A dictionary.keys() N/A

values() N/A N/A N/A dictionary.values() N/A

items() N/A N/A N/A dictionary.items() N/A

capitalize() N/A N/A N/A N/A string.capitalize()

replace() list.replace('old', N/A N/A N/A string.replace('old',


'new') 'new')

Method List Set Tuple Dictionary String

extend() list.extend(['d', N/A N/A N/A N/A


'e'])

pop() item = list.pop() item = N/A item = N/A


set.pop() dictionary.pop(key)

len() length = len(list) length = length = length = length = len(string)


len(set) len(tuple) len(dictionary)

clear() list.clear() set.clear() N/A dictionary.clear() N/A

copy() list_copy = set_copy = N/A dict_copy = N/A


list.copy() set.copy() dict.copy()

find() N/A N/A N/A N/A index =


string.find('substring')

lower() N/A N/A N/A N/A lower_string =


string.lower()

upper() N/A N/A N/A N/A upper_string =


string.upper()
Method List Set Tuple Dictionary String

format() N/A N/A N/A N/A formatted_string =


"Hello, {}".format(name)

get() N/A N/A N/A value = N/A


dictionary.get(key)

reverse() list.reverse() N/A N/A N/A N/A

slice() list_slice = N/A tuple_slice = N/A string_slice =


list[start:stop] tuple[start:stop] string[start:stop]

join() ''.join(list) ''.join(set) N/A N/A 'sep'.join(string)

Method List Set Tuple Dictionary String

append() list.append('i N/A N/A N/A N/A


tem')

clear() list.clear() set.clear() N/A dictionary.clear() N/A

copy() list.copy() set.copy() N/A dictionary.copy() N/A

count() list.count('ite N/A tuple.count('item') N/A string.count('substr


m') ing')

extend() list.extend(['i N/A N/A N/A N/A


tem1',
'item2'])

index() list.index('ite N/A tuple.index('item') N/A string.index('substr


m') ing')

insert() list.insert(ind N/A N/A N/A N/A


ex, 'item')

pop() list.pop(index set.pop(item) N/A dictionary.pop(k N/A


) ey)

remove() list.remove('i set.remove('it N/A N/A N/A


tem') em')

reverse() list.reverse() N/A N/A N/A N/A

sort() list.sort() N/A N/A N/A N/A

add() N/A set.add('item') N/A N/A N/A

difference() N/A setA.differenc N/A N/A N/A


e(setB)

intersection() N/A setA.intersecti N/A N/A N/A


on(setB)

Method List Set Tuple Dictionary String

isdisjoint() N/A setA.isdisjoint( N/A N/A N/A


setB)

issubset() N/A setA.issubset( N/A N/A N/A


setB)

issuperset() N/A setA.issuperse N/A N/A N/A


t(setB)

symmetric_diffe N/A setA.symmetri N/A N/A N/A


rence() c_difference(s
etB)

union() N/A setA.union(set N/A N/A N/A


B)

update() N/A setA.update(s N/A dictionary.updat N/A


etB) e(dictB)

capitalize() N/A N/A N/A N/A string.capitalize()

casefold() N/A N/A N/A N/A string.casefold()

center() N/A N/A N/A N/A string.center(width


)

encode() N/A N/A N/A N/A string.encode()

endswith() N/A N/A N/A N/A string.endswith(su


ffix)

expandtabs() N/A N/A N/A N/A string.expandtabs(t


absize)

find() N/A N/A N/A N/A string.find(substrin


g)

format() N/A N/A N/A N/A string.format()

isalnum() N/A N/A N/A N/A string.isalnum()

isalpha() N/A N/A N/A N/A string.isalpha()

isdecimal() N/A N/A N/A N/A string.isdecimal()

isdigit() N/A N/A N/A N/A string.isdigit()

isidentifier() N/A N/A N/A N/A string.isidentifier()

islower() N/A N/A N/A N/A string.islower()

isnumeric() N/A N/A N/A N/A string.isnumeric()

isprintable() N/A N/A N/A N/A string.isprintable()


isspace() N/A N/A N/A N/A string.isspace()

Method List Set Tuple Dictionary String

istitle() N/A N/A N/A N/A string.istitle()

isupper() N/A N/A N/A N/A string.isupper()

join() N/A N/A N/A N/A string.join(iterable)

ljust() N/A N/A N/A N/A string.ljust(width)

lower() N/A N/A N/A N/A string.lower()

lstrip() N/A N/A N/A N/A string.lstrip([chars]


)

maketrans() N/A N/A N/A N/A string.maketrans(x[


, y[, z]])

partition() N/A N/A N/A N/A string.partition(sep


)

replace() N/A N/A N/A N/A string.replace(old,


new[, count])

rfind() N/A N/A N/A N/A string.rfind(sub[,


start[, end]])

rindex() N/A N/A N/A N/A string.rindex(sub[,


start[, end]])

rjust() N/A N/A N/A N/A string.rjust(width[,


fillchar])

rpartition() N/A N/A N/A N/A string.rpartition(se


p)

rsplit() N/A N/A N/A N/A string.rsplit(sep=N


one, maxsplit=-1)

rstrip() N/A N/A N/A N/A string.rstrip([chars]


)

split() N/A N/A N/A N/A string.split(sep=No


ne, maxsplit=-1)

splitlines() N/A N/A N/A N/A string.splitlines([ke


epends])

startswith() N/A N/A N/A N/A string.startswith(pr


efix[, start[, end]])

strip() N/A N/A N/A N/A string.strip([chars])

swapcase() N/A N/A N/A N/A string.swapcase()


title() N/A N/A N/A N/A string.title()

Method List Set Tuple Dictionary String

translate() N/A N/A N/A N/A string.translate(tab


le)

upper() N/A N/A N/A N/A string.upper()

zfill() N/A N/A N/A N/A string.zfill(width)

You might also like