There are many in-built features APIs in python which we can use to process the given string. Following are a few examples.
Remove whitespace characters from a string
inputString = "Hello world!, How are you?" finalString = ''.join(inputString.split()) print(finalString)
The split() function is used to separate the given string based on the delimiter. By default, the split() function uses the space as a delimiter.
In the above API, split and separate each character in the string by ignoring all the white spaces. Later join() function joins the output characters with empty characters to form a complete string without whitespace.
Remove characters from a string
input = "Hello world how are you?" # Prints last 6 characters outputString = input[:6] print(outputString) # Prints first 4 characters print(input[:6]) print(outputString) # Prints characters from 6th index to the 10th index print(input[6:10]) print(outputString)
The above operations are known as slicing operations which are equivalent to the following
a[slice(start, stop, step)]
Slice has optional parameters i.e. you do not need to pass all three parameters. Not all objects need to be passed every time. Both of the following are accepted.
input[slice(stop)] input[slice(start)] input[slice(start, stop[, step])
The ":" represents the simple use of slicing which is equivalent to the slice() operation.
Convert lower case to upper case and vice-versa
inputString = "lowercasestring" print(inputString.upper()) inputString1 = "UPPERCASESTRING" print(inputString.lower())
Upper() is used to convert the lower case string to higher case whereas lower() is to convert characters from upper case to lower case.