1. Write a Python program to remove leading zeros
from an IP address.
import
re
ip
= "216.08.094.196"
string
= re.sub('\.[0]*', '.', ip)
print(string)
2. Write a Python
program to check for a number at the end of a string
import
re
def
end_num(string):
text = re.compile(r".*[0-9]$")
if text.match(string):
return True
else:
return False
print(end_num('abcdef'))
print(end_num('abcdef6'))
3. Write Python
program to search the numbers (0-9) of length between 1 to 3 in a given string.
import
re
results
= re.finditer(r"([0-9]{1,3})", "Exercises number 1, 12, 13, and
345 are important")
print("Number
of length 1 to 3")
for
n in results:
print(n.group(0))
4. Write a Python
program to find the substrings within a string
import
re
text
= 'Python exercises, PHP exercises, C# exercises'
pattern
= 'exercises'
for
match in re.findall(pattern, text):
print('Found "%s"' % match)
5. Write a Python
program to find the occurrence and position of the substrings within a string
import
re
text
= 'Python exercises, PHP exercises, C# exercises'
pattern
= 'exercises'
for
match in re.finditer(pattern, text):
s = match.start()
e = match.end()
print('Found "%s" at %d:%d' % (text[s:e], s, e))
6. Write a Python
program to replace whitespaces with an underscore and vice versa
import
re
text
= 'Python Exercises'
text
=text.replace (" ", "_")
print(text)
text
=text.replace ("_", " ")
print(text)
7. Write a Python
program to extract year, month and date from an url.
import
re
def
extract_date(url):
return re.findall(r'/(\d{4})/(\d{1,2})/(\d{1,2})/', url)
url1=
"https://www.washingtonpost.com/news/football-insider/wp/2016/09/02/odell-beckhams-fame-rests-on-one-stupid-little-ball-josh-norman-tells-author/"
print(extract_date(url1))
8. Write a Python
program to convert a date of yyyy-mm-dd format to dd-mm-yyyy format
import
re
def
change_date_format(dt):
return re.sub(r'(\d{4})-(\d{1,2})-(\d{1,2})', '\3-\2-\1',
dt)
dt1
= "2026-01-02"
print("Original
date in YYY-MM-DD Format: ",dt1)
print("New
date in DD-MM-YYYY Format: ",change_date_format(dt1))
9.Write a Python
program to match if two words from a list of words starting with letter 'P'.
import
re
#
Sample strings.
words
= ["Python PHP", "Java JavaScript", "c c++"]
for
w in words:
m = re.match("(P\w+)\W(P\w+)", w)
# Check for success
if m:
print(m.groups())
10. Write a Python
program to separate and print the numbers of a given string
import
re
#
Sample string.
text
= "Ten 10, Twenty 20, Thirty 30"
result
= re.split("\D+", text)
#
Print results.
for
element in result:
print(element)
11. Write a Python
program to find all words starting with 'a' or 'e' in a given string
import
re
# Input.
text
= "The following example creates an ArrayList with a capacity of 50
elements. Four elements are then added to the ArrayList and the ArrayList is
trimmed accordingly."
#find
all the words starting with ‘a’ or ‘e’
list
= re.findall("[ae]\w+", text)
#
Print result.
print(list)
12. Write a Python
program to separate and print the numbers and their position of a given string.
import
re
#
Input.
text
= "The following example creates an ArrayList with a capacity of 50
elements. Four elements are then added to the ArrayList and the ArrayList is
trimmed accordingly."
for
m in re.finditer("\d+", text):
print(m.group(0))
print("Index position:", m.start())
13. Write a Python
program to abbreviate 'Road' as 'Rd.' in a given string
import
re
street
= '21 Ramkrishna Road'
print(re.sub('Road$',
'Rd.', street))
14. Write a Python
program to replace all occurrences of space, comma, or dot with a colon
import
re
text
= 'Python Exercises, PHP exercises.'
print(re.sub("[
,.]", ":", text))
15. Write a Python
program to find all five characters long word in a string
import
re
text
= 'The quick brown fox jumps over the lazy dog.'
print(re.findall(r"\b\w{5}\b",
text))
16 Write a Python
program to find all three, four, five characters long words in a string.
import
re
text
= 'The quick brown fox jumps over the lazy dog.'
print(re.findall(r"\b\w{3,5}\b",
text))
17. Write a Python
program to remove multiple spaces in a string
import
re
text1
= 'Python Exercises'
print("Original
string:",text1)
print("Without
extra spaces:",re.sub(' +',' ',text1))
18.Write a Python
program to remove all whitespaces from a string
import
re
text1
= ' Python Exercises '
print("Original
string:",text1)
print("Without
extra spaces:",re.sub(r'\s+', '',text1))
19. Write a Python
program to implement pow(x, n).
class
py_solution:
def pow(self, x, n):
if not n:
return 1
if n > 1:
return
eval("{}{}".format(x,"*{}".format(x)*(n-1)))
if n < 1:
return eval("1/({}{})".format(x, "*{}".format(x)
* (-n - 1)))
print(py_solution().pow(2,
-3));
print(py_solution().pow(3,
5));
print(py_solution().pow(100,
0));
20. Write a Python
class named Circle constructed by a radius and two methods which will compute
the area and the perimeter of a circle
class
Circle():
def __init__(self,r):
self.radius = r
def area(self):
return self.radius**2*3.14
def perimeter(self):
return 2*self.radius*3.14
NewCircle
= Circle(8)
print(NewCircle.area())
print(NewCircle.perimeter())
22.Write a Python
program to remove duplicates from Dictionary
dict
= {'one': 1, 'two': 2, 'three': 3, 'four': 1}
#print(dict)
#print(dict.items())
res
= {}
for
key,value in dict.items():
if value not in res.values():
res[key] = value
print(res)
23. Write a Python
program to check a dictionary is empty or not.
my_dict
= {}
if
not bool(my_dict):
print("Dictionary is empty")
else:
print("Dictionary is not empty")
24.Write a Python
program to combine two dictionary adding values for common keys
from
collections import Counter
d1
= {'a': 100, 'b': 200, 'c':300}
d2
= {'a': 300, 'b': 200, 'd':400}
d =
Counter(d1) + Counter(d2)
print(d)
25. Write a Python
program to print all unique values in a dictionary.
L =
[{"V":"S001"}, {"V": "S002"},
{"VI": "S001"}, {"VI": "S005"},
{"VII":"S005"},
{"V":"S009"},{"VIII":"S007"}]
print("Original
List: ",L)
u_value
= set( val for dic in L for val in dic.values())
print("Unique
Values: ",u_value)
26.Write a Python
program to sort a dictionary by key.
color_dict
= {'red' : 1, 'blue': 2, 'orange': 3}
print(color_dict)
print(sorted(color_dict))
for
key in sorted(color_dict):
print("%s : %s" % (key, color_dict[key]))
27.Write a Python
program to sum all the items in a dictionary.
dict
= {'n1': 1, 'n2': 2, 'n3': 3}
print(sum(dict.values()))
No comments:
Post a Comment
Note: only a member of this blog may post a comment.