Question

In: Computer Science

Python please Questions #3, #4 and # 5 please A string is one of most powerful...

Python please Questions #3, #4 and # 5 please

A string is one of most powerful data types in programming. A string object is a sequence of characters and because it is a sequence, it is indexable, using index numbers starting with 0. Similar to a list object, a string object allows for the use of negative index with -1 representing the index of the last character in the sequence. Accessing a string object with an invalid index will result in IndexError exception.

In Python a string literal is defined to be a sequence of characters enclosed in single, double or triple quotes.

To define a string object or variable, we use one of the following:

  1. strObj = string_literal
  2. strObj = str(any object)
  3. strObj = str() or strObj = ‘’, strObj = “”, strObj = ‘’’’’’ , an empty string

A string object in immutable, meaning, it cannot be changed once it is defined.

The concatenation operator (+) is used to add two or more string objects (strObj1 + strObj2)

The repetition operator (*) is used to repeat the string object (n*strObj or strObj*n, where n is an integer)

The in and not in operators are used to test if one string object is contained in another string object.

Slice a string object using strObj[start:end], start is the index of the starting character and end-1 is the index last character.

The split method creates a list of the split string object.

lstObj = strObj.split(split-character)

space is the default split-character.

The strip method removes the leading and trailing character, the default is space.

strObj.strip(strip-character)

Variations: rstrip, lstrip (left and right strip methods to remove leading and trailing character, respectively)

Other commonly used string methods are

strObj.lower() changes all characters to lowercase

strObj.upper() changes all characters to uppercase

strObj.islower() tests if all characters are lowercase

strObj.isupper() tests if all characters are uppercase

strObj.replace(old, new) replaces old substring with new substring

strObj.find(substring) returns the lowest index of the substring if it is found in strObj

Activity

  1. Write a program to reverse a string object
  2. Write a program that will check if a string object is a palindrome, that is a word, phrase, or sequence that reads the same backward as forward, e.g., madam or nurses run. Note: reverse(string) = string.
  3. Define a string object that will hold “department computer science:fayetteville state university:fayetteville, north carolina”
  4. Split the string object in (3) using the character “:” and assign to a list object
  5. Write a program that capitalize the first letter of every word in string object in (3)
  6. Write a program that insert the string objects “of” and “28301” to the new string object in (5)
  7. Write a program that will display the word, character, space counts in the file storytelling.txt.(The file is on Canvas in the Worksheets folder).

Solutions

Expert Solution

1) Write a program to reverse a string object

Ans:

strObj = "Sangeetha"[::-1]
print(strObj)

2) Write a program that will check if a string object is a palindrome, that is a word, phrase, or sequence that reads the same backward as forward, e.g., madam or nurses run. Note: reverse(string) = string.

Ans :

def isPalindrome(strObj):
    return strObj == strObj[::-1]
 
 
strObj = "bananab"
ans = isPalindrome(strObj)
 
if ans:
    print("It is Palindrome")
else:
    print("It is not a Palindrome")

3) Define a string object that will hold “department computer science:fayetteville state university:fayetteville, north carolina”

Ans :

strObj="department computer science:fayetteville state university:fayetteville, north carolina"
print(strObj)

4) Split the string object in (3) using the character “:” and assign to a list object

Ans :

listObj=[]
strObj="department computer science:fayetteville state university:fayetteville, north carolina"
listObj=strObj.split(':')
print(listObj)

5) Write a program that capitalize the first letter of every word in string object in (3)

Ans :

strObj="department computer science:fayetteville state university:fayetteville, north carolina"
listObj=strObj.split(':')
strObj = " ".join(listObj)
lst = [f[0].upper() + f[1:] for f in strObj.split()]
strObj = " ".join(lst)
print(strObj)

6) Write a program that insert the string objects “of” and “28301” to the new string object in (5)

Ans :

strObj="department computer science:fayetteville state university:fayetteville, north carolina"
listObj=strObj.split(':')
strObj = " ".join(listObj)
lst = [f[0].upper() + f[1:] for f in strObj.split()]
strObj = " ".join(lst)
strObj+=" of"
strObj+=" 28301"
print(strObj)

7) Write a program that will display the word, character, space counts in the file storytelling.txt.(The file is on Canvas in the Worksheets folder).

Ans :

def counter(fname): 
    num_words = 0
    num_lines = 0
    num_charc = 0
    num_spaces = 0
    with open(fname, 'r') as f: 
        for line in f: 
            num_lines += 1
            word = 'Y'
            for letter in line: 
                if (letter != ' ' and word == 'Y'): 
                    num_words += 1
                    word = 'N'
                elif (letter == ' '): 
                    num_spaces += 1
                    word = 'Y'
                for i in letter: 
                    if(i !=" " and i !="\n"): 
                        num_charc += 1
    print("Number of words in text file: ", num_words) 
    print('Number of characters in text file: ', num_charc) 
    print('Number of spaces in text file: ', num_spaces) 

if __name__ == '__main__':  
    fname = 'C:\\Users\\Worksheets\\storytelling.txt'
    try:  
        counter(fname)  
    except:  
        print('File not found') 

Related Solutions

Python please Questions #6 and # 7 please A string is one of most powerful data...
Python please Questions #6 and # 7 please A string is one of most powerful data types in programming. A string object is a sequence of characters and because it is a sequence, it is indexable, using index numbers starting with 0. Similar to a list object, a string object allows for the use of negative index with -1 representing the index of the last character in the sequence. Accessing a string object with an invalid index will result in...
Python please A string is one of most powerful data types in programming. A string object...
Python please A string is one of most powerful data types in programming. A string object is a sequence of characters and because it is a sequence, it is indexable, using index numbers starting with 0. Similar to a list object, a string object allows for the use of negative index with -1 representing the index of the last character in the sequence. Accessing a string object with an invalid index will result in IndexError exception. In Python a string...
Economies of scale are one of the most powerful forces in economics. Answer the following questions...
Economies of scale are one of the most powerful forces in economics. Answer the following questions related to this very important principle of economics: A. Explain how economies of scale are particularly important to a monopolist, be they real (in reality, there are very few examples of monopoly in the real economy) or hypothetical. B. Building on question (a.) above, in the event that a new competitor decided to enter this otherwise monopolistic market and building on their natural competitive...
python 3 please Define a function voweliest that takes as input a string and returns as...
python 3 please Define a function voweliest that takes as input a string and returns as output a tuple where the string that has the most vowels in it is the first element and the second is the number of vowels in that string. Note: don't worry about ties or capital letters Hint: consider defining and using a separate function that counts the number of vowels in a given string
PLEASE answer questions 3 , 4 & 5. write clearly PROBLEM 3 Calculate the magnitude of...
PLEASE answer questions 3 , 4 & 5. write clearly PROBLEM 3 Calculate the magnitude of the gravitational force on a cantaloupe of mass m = 873 g on the surface of the Earth due to (a) the Earth (b) the Moon (c) the Sun PROBLEM 4 A hypothetical planet has 1/5 of the diameter of the Earth, and its density is 4 times larger (compared to the Earth). Find its total mass and the free fall acceleration. PROBLEM 5...
Please provide Python code that does the following: 3) Write a program that takes a string...
Please provide Python code that does the following: 3) Write a program that takes a string as input, checks to see if it is comprised entirely of letters, and if all those letters are lower case. The output should be one of three possible messages: Your string is comprised entirely of lower case letters. Your string is comprised entirely of letters but some or all are upper case. Your string is not comprised entirely of letters. Your program may NOT:...
For questions 3 and 4, please remember that only one RNA strand is being synthesized, and...
For questions 3 and 4, please remember that only one RNA strand is being synthesized, and only the template strand of the DNA is being transcribed. 3. (3 points) E. coli RNA polymerase adds ribonucleotides to an RNA strand at a rate of 22 per second. The size of the transcribed region of the largest gene in E. coli is 1538 bp. How long (in seconds) will it take RNA polymerase to complete transcription of an average-sized gene? (Round off...
PYTHON PLEASE: Construct a class “Monster” with the following attributes: self.name (a string) self.type (a string,...
PYTHON PLEASE: Construct a class “Monster” with the following attributes: self.name (a string) self.type (a string, default is ‘Normal’) self.current_hp (int, starts out equal to max_hp) self.max_hp (int, is given as input when the class instance is created, default is 20) self.exp (int, starts at 0, is increased by fighting) self.attacks (a dict of all known attacks) self.possible_attacks (a dictionary of all possible attacks) The dictionary of possible_attacks will map the name of an attack (the key) to how many...
Write a Python program that has a list of 5 numbers [2, 3, 4, 5, 6)....
Write a Python program that has a list of 5 numbers [2, 3, 4, 5, 6). Print the first 3 elements from the list using slice expression. a. Extend this program in a manner that the elements in the list are changed to (6, 9, 12, 15, 18) that means each element is times 3 of the previous value. b. Extend your program to display the min and max value in the list.
Please provide answers next to the questions provided. Most questions can be answered with 3 or...
Please provide answers next to the questions provided. Most questions can be answered with 3 or less sentences, but please do not exceed 5 sentences What in your opinion is the biggest reason for information risk? Does auditing eliminate information risk specifically related to your previous answer? Explain your answers . What is the difference between assurance services and non-assurance services that auditing firms can provide? Which category does attestation services belong to (i.e. assurance or non-assurance) and why is...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT