w3resource

Python: Get a new string from a given string where 'Is' has been added to the front. If the given string already begins with 'Is' then return the string unchanged

Python Basic: Exercise-19 with Solution

Write a Python program to get a newly-generated string from a given string where "Is" has been added to the front. Return the string unchanged if the given string already begins with "Is".

Pictorial Presentation:

Get a new string from a given string where 'Is' has been added to the front. If the given string already begins with 'Is' then return the string unchanged

Sample Solution:

Python Code:

# Define a function named "new_string" that takes a string parameter called "text"
def new_string(text):
    # Check if the length of the "text" is greater than or equal to 2 and if the first two characters of "text" are "Is"
    if len(text) >= 2 and text[:2] == "Is":
        # If the conditions are met, return the original "text" unchanged
        return text
    else:
        # If the conditions are not met, prepend "Is" to the "text" and return the modified string
        return "Is" + text

# Call the "new_string" function with the argument "Array" and print the result
print(new_string("Array"))

# Call the "new_string" function with the argument "IsEmpty" and print the result
print(new_string("IsEmpty"))

Sample Output:

IsArray                                                                                                       
IsEmpty

Explanation:

The said script defines a function "new_string(text)" takes a string as an argument, and checks whether the string's length is greater than or equal to 2 and the first two characters of the string are "Is". If both conditions are true, the function returns the original string. Otherwise, the function returns a new string "Is" concatenated with the original string.

The first print statement will display "IsArray" and the second will display "IsEmpty".

Flowchart:

Flowchart: Get a new string from a given string where 'Is' has been added to the front. If the given string already begins with 'Is' then return the string unchanged.

Python Code Editor:

 

Previous: Write a Python program to calculate the sum of three given numbers, if the values are equal then return thrice of their sum.
Next: Write a Python program to get a string which is n (non-negative integer) copies of a given string.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.