KnowledgeBoat Logo

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