Beruflich Dokumente
Kultur Dokumente
+ Concatenates string1 +
(joins) string1 and string2 string2
a = "Bee " * 3
print(a)
RESULT
Bee Bee Bee
a = "Sea"
print(a[1])
RESULT
e
a = "Mushroom"
print(a[4:8])
RESULT
room
In Membership — x in string
Returns True if x exists in the string.
Can be multiple characters.
a = "Mushroom"
print("m" in a)
print("b" in a)
print("shroo" in a)
RESULT
True
False
True
a = "Mushroom"
print("m" not in a)
print("b" not in a)
print("shroo" not in a)
RESULT
False
True
False
strip()
This function is used to remove white spaces from the given string.
Syntax
stringVariable.strip()
Code
Output
lower()
This function is used to convert a string into lower case.
Syntax
stringVariable.lower()
Code
Output
upper()
This function is used to convert a string into uppercase.
Syntax
print(string.upper())
Code
Output
len()
This function returns the length of the given string.
Syntax
len(stringVariable)
Code
Output
replace()
This function is used to replace a string with another string.
Syntax
stringVariable("replaceString","withnewString")
Code
Output
split()
This function splits the string into a substring if any separator is available.
Syntax
string_variable.split("seperator")
Code
Output
title()
This function returns the first letter of each word in uppercase.
Syntax
stringVeriable.title()
Code
Output
In the above code the first letter in each word is the lower case; after using title(), it converts
the whole text into title format.
capitalize()
This function is used for converting the first character into an upper case.
Syntax
variable.capitalize()
Code
Output
count()
This function returns the occurrence of subsisting in a string.
Syntax
variable.count('string')
Code
Output
find()
This function returns in which index your search text is available in the given string.
Note
Syntax
stringVariable.find("searchText")
Code
Output
1. if statements
2. if-else statements
1. if Statements In Python
if(condition):
statements
apple = 2
if (apple == 2):
print('You have two apple')
Run Code
Output
If else statements will execute one block of statements if condition is true else another block
of statement will be executed.
if-else statements
if(condition):
statements
else:
statements
Run Code
Output :-
If (condition):
statements
elif (condition):
statements
else:
statements
When one condition is true its respective block of statement will be executed remaining
conditions will be bypassed
Example of Nested if-else statement In Python
age =19
if(age < 18):
print('you are under 18')
elif(age == 18):
print('you are 18')
else:
print('you are above 18')
Run Code
Output :-
We can import a module using the import statement and access the definitions inside it
using the dot operator as described above. Here is an example.
import math
print("The value of pi is", math.pi)
import math as m
print("The value of pi is", m.pi)
We have renamed the math module as m. This can save us typing time in some cases.
Note that the name math is not recognized in our scope. Hence, math.pi is invalid,
and m.pi is the correct implementation.
We can import specific names from a module without importing the module as a whole.
Here is an example.
# import only pi from math module
We can import all names(definitions) from a module using the following construct:
Here, we have imported all the definitions from the math module. This includes all names
visible in our scope except those beginning with an underscore(private definitions).
Importing everything with the asterisk (*) symbol is not a good programming practice.
This can lead to duplicate definitions for an identifier. It also hampers the readability of
our code.
Here when the function is called the parameters are passed and the
respective tasks are performed. Once the return statement is
encountered the value that is to be returned, is returned to the place
from where it was called and the code ahead continues to execute
7) Explain with an example program to return the average of its argument.
In this program the user enters 4 numbers and these number are
passed to a function called 'average' and the function calculates the
average of these numbers are then returned to where it was called.
The numbers are passed to the function as parameters.
Problem Description
The program takes a number and checks whether it is a palindrome or not.
Problem Solution
1. Take the value of the integer and store in a variable.
2. Transfer the value of the integer into another temporary variable.
3. Using a while loop, get each digit of the number and store the reversed number in
another variable.
4. Check if the reverse of the number is equal to the one in the temporary variable.
5. Print the final result.
6. Exit.
Program:
n=int(input("Enter number:"))
temp=n
rev=0
while(n>0):
dig=n%10
rev=rev*10+dig
n=n//10
if(temp==rev):
print("The number is a palindrome!")
else:
print("The number isn't a palindrome!")
Program Explanation
1. User must first enter the value of the integer and store it in a variable.
2. The value of the integer is then stored in another temporary variable.
3. The while loop is used and the last digit of the number is obtained by using the
modulus operator.
4. The last digit is then stored at the one’s place, second last at the ten’s place and
so on.
5. The last digit is then removed by truly dividing the number with 10.
6. This loop terminates when the value of the number is 0.
7. The reverse of the number is then compared with the integer value stored in the
temporary variable.
8. If both are equal, the number is a palindrome.
9. If both aren’t equal, the number isn’t a palindrome.
10. The final result is then printed.
Output 1:
Enter number:121
The number is a palindrome!
Output 2:
Enter number:567
The number isn't a palindrome!
9) Demonstrate the use of break and continue keywords in looping constructs
using a snippet code.
If you specify an index, you’ll get the character at that position in the
string. If you specify a range from one index to another, the starting index
is included and the ending index is not. That’s why, if spam is 'Hello world!',
spam[0:5] is 'Hello'. The substring you get from spam[0:5] will include everything
from spam[0] to spam[4], leaving out the space at index 5.
Note that slicing a string does not modify the original string. You can
capture a slice from one variable in a separate variable
>>> spam[0:5]
'Hello'
>>> spam[:5]
'Hello'
>>> spam[6:]
'world!'
>>> spam = 'Hello world!'
>>> fizz = spam[0:5]
>>> fizz
'Hello'
y slicing and storing the resulting substring in another variable, you can
have both the whole string and the substring handy for quick, easy access.
def LongestWordLength(str):
n = len(str)
res = 0; curr_len = 0
# If current character is
# not end of current word.
if (str[i] != ' '):
curr_len += 1
# Driver Code
s = input('Enter a sentence: ')
print('The length of the longest word in the string is:',LongestWordLength(s))
12) List and explain the string manipulation functions supported in python
To manipulate strings, we can use some of Pythons built-in methods.
Creation
word = "Hello World"
>>> print word
Hello World
Accessing
Use [ ] to access characters in a string
word = "Hello World"
letter=word[0]
>>> print letter
H
Length
word = "Hello World"
>>> len(word)
11
Finding
word = "Hello World">>> print word.count('l') # count how many times l is in the string
3
>>> print word.find("H") # find the word H in the string
0
>>> print word.index("World") # find the letters World in the string
6
Count
s = "Count, the number of spaces"
>>> print s.count(' ')
8
Slicing
Use [ start : end ] to get set of letter
word = "Hello World"
13) Write the python code to display the last six characters of the string
‘Many hay while the sun shines’ to the console.
def word_count(fname):
with open(fname) as f:
return Counter(f.read().split())
Escape Characters
To insert characters that are illegal in a string, use an escape character.
Example
You will get an error if you use double quotes inside a string that is
surrounded by double quotes:
Example
The escape character allows you to use double quotes when you
normally would not be allowed:
txt = "We are the so-called \"Vikings\" from the north."
18) The string value "Howl's Moving Castle" is a valid string. Why
isn’t it a problem that the single quote character in the word Howl's
isn’t escaped?
19. If you don’t want to put \n in your string, how can you write a string
with newlines in it?
20. What do the following expressions evaluate to?
• 'Hello world!'[1]
• 'Hello world!'[0:5]
• 'Hello world!'[:5]
• 'Hello world!'[3:]
The dot matches a single character, without caring what that character
is. The only exception are line break characters. In all regex flavors
discussed in this tutorial, the dot does not match line breaks by default.
This exception exists mostly because of historic reasons.
16) What is the difference between .* and .*? ?
import re
string='abbcccdefghcccddd'
pattern1='a(.*)ccc'
pattern2='a(.*?)ccc'
match=re.search(pattern1,string)
print(match.group())
match=re.search(pattern2,string)
print(match.group())
Output:
abbcccdefghccc
abbccc
.* is a greedy mode, which tends to get the longest string that meets the conditions;
.*? is a non-greedy mode, which tends to get the shortest string that can meet the
conditions.
Numbers
[0-9]
Match any digit; same as [0123456789]
Lowercase letters
[a-z]
code:
import re
def printMatch(name):
pat = re.compile(r'\b[A-Z][a-zA-Z]+\sNakamoto')
if pat.search(name):
print(''+name+' matches')
else:
print(''+name+' does not match')
23. How would you write a regex that matches a sentence where the first word
is either Alice, Bob, or Carol; the second word is either eats, pets, or throws; the
third word is apples, cats, or baseballs; and the sentence ends with a period?
This regex should be case-insensitive. It must match the following:
• 'Alice eats apples.'
• 'Bob pets cats.'
• 'Carol throws baseballs.'
• 'Alice throws Apples.'
• 'BOB EATS CATS.'
but not the following:
• 'RoboCop eats apples.'
• 'ALICE THROWS FOOTBALLS.'
• 'Carol eats 7 cats.'
re.compile(r'(Alice|Bob|Carol)\s+(eats|pets|throws)\s+(apples|cats|baseballs
)\.', re.IGNORECASE)
29. Implement the python program using Lists to store and display the average
of N integers accepted from the user.
PROGRAM:
lst = []
print("Enter the number and type done to compute:")
while True:
n = input();
if n == "done":
break;
else:
lst.append(int(n))
if (len(lst)):
average = sum(lst)/len(lst)
print("List of numbers: ",format(lst))
print("Average: ",average )
else:
print("Please enter the numbers.")
OUTPUT:
Enter the number and type done to compute:
40
40
40
done
List of numbers: [40, 40, 40]
Average: 40.0
Creating a Dictionary:
# Creating an empty Dictionary
Dict = {}
print(Dict)
print(Dict)
print(Dict)
print(Dict)
print(Dict)
OUTPUT:
Empty Dictionary:
{}
print(Dict.get(3))
OUTPUT:
Accessing a element using key:
For
Accessing a element using get:
Geeks
31. Write python program to search for lines that start with the word ‘From’
and a character followed by a two digit number from 00 and 99 followed by ‘:’
Print the number if it is greater than zero. Assume the input file.
import re
hand = open('mbox-short.txt')
for line in hand:
line = line.rstrip()
x = re.findall('^From .* ([0-9][0-9]):', line)
if len(x) > 0: print(x)
OUTPUT:
['09']
['18']
['16']
['15']
...
32. Describe any 2 List Operations and List methods. Write a python program
to accept ‘n’ numbers from user, find sum of all even numbers and product of
odd numbers entered in the list.
List Operations:
i. The + operator concatenates lists:
>>> a = [1, 2, 3]
>>> b = [4, 5, 6]
>>> c = a + b
>>> c
[1, 2, 3, 4, 5, 6]
ii. The * operator repeats a list a given number of times:
>>> [0] * 4
[0, 0, 0, 0]
>>> [1, 2, 3] * 3
[1, 2, 3, 1, 2, 3, 1, 2, 3]
The first example repeats [0] four times. The second example repeats the
list [1, 2, 3] three times.
List Methods:
• append(): Used for appending and adding elements to List. It is used to add
elements to the last position of List
Syntax: list.append(element)
• insert(): Inserts an elements at specified position.
Syntax: list.insert( position, element)
OUPUT:
33. List merits of Dictionaries over the List. Write a python program to accept
USN and marks obtained, find Maximum and Minimum and Students USN
who have scored in the range 100-85, 85-75, 75-60 and below 60 marks
separately.
print("Type done when done")
dic={}
while True:
usn = input("USN: ")
if usn=='done':
break;
mar = input("Marks: ")
if usn in dic:
print("Duplicate of USN")
else:
dic[usn]=int(mar)
high = 0
highUSN = None
low = 100
lowUSN = None
for i in dic:
if high<dic[i]:
high=dic[i];
highUSN=i;
if low>dic[i]:
low=dic[i];
lowUSN=i;
if dic[i] >= 85 and dic[i]<=100:
print("Range 100-85: USN: {} Marks: {}".format(i,dic[i]))
elif dic[i] >= 75 and dic[i]<85:
print("Range 85-75: USN: {} Marks: {}".format(i,dic[i]))
elif dic[i] >= 60 and dic[i]<75:
print("Range 75-60: USN: {} Marks: {}".format(i,dic[i]))
elif dic[i]<60:
print("Range Below 60: USN: {} Marks: {}".format(i,dic[i]))
print("\n\nHighest is {} scored {}".format(highUSN,high))
print("Lowest is {} scored {}".format(lowUSN,low))
OUTPUT:
USN: 1DT18IS123
Marks: 95
USN: 1DT18IS234
Marks: 83
USN: 1DT18IS345
Marks: 73
USN: 1DT18IS456
Marks: 63
USN: 1DT18IS567
Marks: 53
USN: done
34. Compare and contrast tuples and lists. Explain the following operations in
tuples.
i. Sum of two tuples.
ii. Slicing operators.
iii. Comparison of 2 tuples
iv. Assignments to variables
i. Sum of two tuples:
# initialize tuples
test_tup1 = (10, 4, 5)
test_tup2 = (2, 5, 18)
# Addition of tuples
# using map() + lambda
res = tuple(map(lambda i, j: i + j, test_tup1, test_tup2))
# printing result
print("Resultant tuple after addition : " + str(res))
Output :
The original tuple 1 : (10, 4, 5)
The original tuple 2 : (2, 5, 18)
Resultant tuple after addition : (12, 9, 23)
ii. Slicing Operators:
The slice() function returns a slice object.
A slice object is used to specify how to slice a sequence. You can specify where
to start the slicing, and where to end. You can also specify the step, which
allows you to e.g. slice only every other item.
Syntax:
slice(start, end, step)
Storage location(s) denoted by a variable name; in other words, it copies a value into the variable.
fundamental construct.