Computer Science
Explain the given built-in string functions and provide the syntax and example of each.
(a) replace()
(b) title()
(c) partition()
Python String Manipulation
1 Like
Answer
(a) replace() — This function replaces all the occurrences of the old string with the new string. The syntax is str.replace(old, new)
.
For example,
str1 = "This is a string example"
print(str1.replace("is", "was"))
Output
Thwas was a string example
(b) title() — This function returns the string with first letter of every word in the string in uppercase and rest in lowercase. The syntax is str.title()
.
For example,
str1 = "hello ITS all about STRINGS!!"
print(str1.title())
Output
Hello Its All About Strings!!
(c) partition() — The partition()
function is used to split the given string using the specified separator and returns a tuple with three parts: substring before the separator, separator itself, a substring after the separator. The syntax is str.partition(separator)
, where separator argument is required to separate a string. If the separator is not found, it returns the string itself followed by two empty strings within parenthesis as tuple.
For example,
str3 = "xyz@gmail.com"
result = str3.partition("@")
print(result)
Output
('xyz', '@', 'gmail.com')
Answered By
3 Likes
Related Questions
Draw a flow chart to print even numbers from 2 to 10 using the loop approach and provide its algorithm.
What will be the output of the following code? Also, give the minimum and maximum values of the variable x.
import random List = ["Delhi", "Mumbai", "Chennai", "Kolkata"] for y in range(4): x = random.randint(1, 3) print(List[x], end = "#")
Write a program to count the frequency of a given element in a list of numbers.
Write a program to check if the smallest element of a tuple is present at the middle position of the tuple.