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

# Strip() Examples

word1 = '   h ello   '
# 3 spaces then h ello then 3 spaces
print('word1.lstrip():', word1.lstrip(), 'world.')
print('word1.rstrip():', word1.rstrip(), 'world.')
print('word1.strip():', word1.strip(), 'world.')
word1.lstrip(): h ello    world.
word1.rstrip():    h ello world.
word1.strip(): h ello world.

Using 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 the new_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()

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 the sequence/iterable_data separated by the str_data provided

  • Each 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 list

  • Both arguments are optional, and when they are not specified: they will separate by spaces

    • pattern : this looks for a pattern to separate each items by

    • numberOfTime : this integer sets how many times to separate the string

Last updated