String Methods Extended
The string data type has a lot of useful built-in methods that can help us solve more complex problems.
Removing Leading and/or Trailing Spaces
These methods do not remove spaces within the text.
string_data.strip()
Returns a string that loses all leading and trailing white spaces
string_data.lstrip()
Returns a string that loses all leading white spaces
string_data.rstrip()
Returns a string that loses all trailing white spaces
Using replace()
replace()
replace()
is a powerful function helps us modify a string by targeting a pattern.
string_data.replace(old_str, new_str, limit)
Returns a new string that replaces all instances of the
old_str
with thenew_str
Limit (optional argument) doesnāt have to be set, if it is set, it will only apply the replace method based on the limit
Therefore, this method can either use either 2 or 3 arguments
Using startswith()
and endswith()
startswith()
and endswith()
String methods that can check the start or the end of a string.
string_data.startswith('pattern', start_index, end_index)
string_data.endswith('pattern', start_index, end_index)
Both of these methods return either True/False
It looks for the string pattern argument either at the start or the end.
The indexes of start and/or end are both optional
they are integer based arguments
Items in a Sequence to String
str_data.join(iterable_data)
the
join()
method returns a new string that combines all items in thesequence/iterable_data
separated by thestr_data
providedEach item in the sequence/iterable data must be a string type
String to a List
There are many ways to convert a string data into a list.
list()
function
This function allows to convert a string to a list
Each individual characters will be separated as a single item in the list
sorted()
function
This function will sort the given string in ASCII order
The function will return a list
Each individual character in the string will be an item in the list
Controlled Way to convert a string to a list: split()
str_data.split('pattern', numberOfTime)
The
split()
method separates a string into a listBoth arguments are optional, and when they are not specified: they will separate by spaces
pattern
: this looks for a pattern to separate each items bynumberOfTime
: this integer sets how many times to separate the string
Last updated