InterviewSolution
| 1. |
String Manipulation in Python |
||||||||||||||||||||
Answer»
Escape Sequences are used to print certain characters to the output stream which carry special meaning to the language compiler. Examples:
Multiline Strings are used in python through triple quotes ''' Example: a = ''' HelloWorld! This is a Multiline String.''' print(a) Output: Hello World! This is a Multiline String.
Strings in Python are indexed the same way as a list of characters, based on 0-based indexing. We can access elements of a string at some index by using the [] operators. Consider an example of the string value Python. a = "Python"print(a[0], a[2], a[4]) print(a[-1], a[-3], a[-5]) Output: P t o n h y
Slicing is also done the same way as in lists. a = "Hello"# Slices the string from 0 to 3 indexes print(a[0:3]) # Slices the string from 3 to -1(same as 4) indexes print(a[3:-1]) Output: Hel l
The upper() and lower() functions are used to convert a string of letters into uppercase or lowercase respectively. The isupper() and islower() functions are used to check if a string is in all uppercase or lowercase respectively. a = "Hello"print(a) # Converts string to uppercase print(a.upper()) # Converts string to lowercase print(a.lower()) # Checks if string is uppercase print(a.isupper()) # Checks if string is lowercase print(a.islower()) Output: Hello HELLO hello False False Other similar functions:
join() function merges elements of a list with some delimiter string, and returns the result as a string. list = ["One", "Two", "Three"]# join function s = ','.join(list) print(s) Output: One,Two,Three split() function splits the into tokens, based on some delimiters and returns the result as a list. # split functionnewList = s.split(',') print(newList) Output: ['One', 'Two', 'Three'] In general, a string can be split to list using split() method and a list can be joined to string using the join() method as shown in the image below:
String Formatting is done with the str.format() function. first = "first"second = "second" s = "Sunday is the {} day of the week, whereas Monday is the {} day of the week".format(first, second) print(s) Output: Sunday is the first day of the week, whereas Monday is the second day of the week
It is recommended to be used when formatting strings generated by users. They make the code less complex so are easier to understand. They can be used by importing the Template class from the string module. Example: >>> from string import Template>>> name = 'Scaler' >>> t = Template('Hey $name!') >>> t.substitute(name = name) 'Hey Scaler!' |
|||||||||||||||||||||