In: Computer Science
IN PYTHON
Complete the following tasks, either in a file or directly in the Python shell.
Using the string class .count() method, display the number of occurrences of the character 's' in the string "mississippi".
Replace all occurrences of the substring 'iss' with 'ox' in the string "mississippi".
Find the index of the first occurrence of 'p' in the string "mississippi".
Determine what the following Python function does and describe it to one of your Lab TAs :
def foo(istring):
p = '0123456789'
os = ''
for iterator in istring:
if iterator not in p:
os += iterator
return os
The answer to the above problem is as follows:
QUESTION - Using the string class .count() method, display the number of occurrences of the character 's' in the string "mississippi".
PYTHON CODE-
s = 'mississippi' #store the string
#use the count() to count occurences of 's' and print the
value
print(s.count('s'))
IMAGE OF CODE and OUTPUT-
QUESTION - Replace all occurrences of the substring 'iss' with 'ox' in the string "mississippi".
PYTHON CODE-
s = 'mississippi' #store the string
#use the replace() to replace occurences of 'iss' with 'ox'
print(s.replace('iss','ox'))
IMAGE OF CODE and OUTPUT-
QUESTION - Find the index of the first occurrence of 'p' in the string "mississippi"
PYTHON CODE-
s = 'mississippi' #store the string
#use the find() to find first occurence of 'p' in string
print(s.find('p'))
IMAGE OF CODE and OUTPUT-
QUESTION - Determine what the following Python function does and describe it to one of your Lab TAs
The above code fragment does the following -
Takes a string as parameter
And then iterates over the string character by character
and if the character is not a digit,ie, not a character in 0123456789, which means not a digit, -> then add this letter to the output string
and after the whole istring is iterated, then returns the output string(os).
For example, if input string istring = 'a1b2c3'
Then it gets consumed by function foo()
Then istring is iterated, so first letter 'a' is checked if its a digit or not, ie, present in '0123456789' or not
And since 'a' is not a digit, it gets concatenated to output string os.
So. only 'a', 'b' and 'c' were concatenated, and '1','2',and '3' were not included.
So output string os = 'abc'
Feel free to comment for any query.