3.4. String methods#

  • We have already encountered functions: built-in functions and functions we have defined. A method is another kind of function that is attached to a particular type. This section covers the methods that are attached to string types.

  • Method calls in this form—'browning'.capitalize()—are shorthand for this: str.capitalize('browning').

  • Methods are like functions, except that the first argument must be an object of the class in which the method is defined.

3.4.1. Strip Methods#

  • strip() – Strip spaces on the left and right of string

my_string = '   ABBCCC  '
print(my_string, 'Dummy')
print(my_string.strip())
   ABBCCC   Dummy
ABBCCC
  • strip(chars) – Strip chars on the left and right of string

my_string = 'ABBCCCA'
print(my_string.strip('A'))
my_string = '  ABBCCCA'
print(my_string.strip('A'))
BBCCC
  ABBCCC
  • lstrip() – Strip spaces from the left of string

my_string = '   ABBCCC  '
print(my_string, 'Dummy')
print(my_string.lstrip(), 'Dummy')
   ABBCCC   Dummy
ABBCCC   Dummy
  • rstrip() – Strip spaces from the right of string

my_string = '   ABBCCC  '
print(my_string, 'Dummy')
print(my_string.rstrip(), 'Dummy')
   ABBCCC   Dummy
   ABBCCC Dummy

3.4.2. Case Methods#

  • islower() – Check if all alphabet characters are lower case

my_string = 'EAS503'
print(my_string.islower())
False
  • isupper() – Check if all alphabet characters are upper case

my_string = 'EAS503'
print(my_string.isupper())
True
  • lower() – Lower case the string; returns a new string

my_string = 'EAS503'
print(my_string.lower())
eas503
  • upper() – Upper case the string; returns a new string

my_string = 'eas503'
print(my_string.upper())
EAS503
  • title() – Make the first letter of each word upper case

my_string = 'the lazy dog jumped over the quick brown fox'
print(my_string.title())
The Lazy Dog Jumped Over The Quick Brown Fox
  • capitalize() – Make the first letter upper case

my_string = 'the lazy dog jumped over the quick brown fox'
print(my_string.capitalize())
The lazy dog jumped over the quick brown fox
  • swapcase() – Make upper case lower case and lower case upper case

my_string = 'tHe laZy dOg Jumped oveR thE quIck bRown Fox'
print(my_string.swapcase())
ThE LAzY DoG jUMPED OVEr THe QUiCK BrOWN fOX

3.4.3. Content Methods#

  • isalpha() – Returns True if all the characters are alphabet

my_string = 'EAS503'
print(my_string.isalpha())
my_string = 'EAS'
print(my_string.isalpha())
False
True
  • isdecimal() – Returns True if all the characters are numbers (0-9); USE THIS!

  • isdigit() – Returns True if all the characters are numbers (0-9), superscripts ("\u00B2"), or fractions '\u00BC';

  • isnumeric() – Returns True if all the characters are numbers (0-9), superscripts ("\u00B2"), fractions '\u00BC', or Roman Numerals!

  • isalnum() – Returns True if the string is alpha numeric

my_string = 'EAS503'
print(my_string.isalnum())
True
  • startswith(substring) – Returns True if the string starts with the specific input argument

my_string = 'EAS503'
print(my_string.startswith('EAS'))
True
  • endswith(substring) – Returns True if the string ends with the specific input argument

my_string = 'EAS503'
print(my_string.endswith('03'))
True
  • find(substring) – Returns the index if the character is found; otherwise returns -1

my_string = 'ABBCCC'
print(my_string.find('BB'))
print(my_string.find('B'))
print(my_string.find('AC'))
1
1
-1
  • index(substring) – Returns the index if the character is found; otherwise raises an error

my_string = 'ABBCCC'
print(my_string.index('BB'))
print(my_string.index('B'))
1
1
my_string = 'ABBCCC'
print(my_string.index('AC'))
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
Cell In[18], line 2
      1 my_string = 'ABBCCC'
----> 2 print(my_string.index('AC'))

ValueError: substring not found
  • in operator – Returns True if the operand on the left exists in the string

my_string = 'ABBCCC'
print('A' in my_string)
True
  • count(substring) – Returns the number of times the substring occurs

my_string = 'ABBCCC'
print(my_string.count('C'))
print(my_string.count('CC'))
print(my_string.count('CCC'))
3
1
1

3.4.4. Modification Methods#

  • replace() – Replaces character(s) with other character(s); returns a new string

  • Given (EAS503), how can you remove the parentheses?

my_string = '(EAS503)'
tmp1 = my_string.replace('(', '')
print(tmp1)
tmp2 = tmp1.replace(')', '')
print(tmp2)
EAS503)
EAS503
  • You can chain methods! Chaining lets you avoid having to save intermediate results.

my_string = '(EAS503)'
print(my_string.replace('(', '').replace(')', ''))
EAS503
  • zfill(number_of_zeros) – prepend zeros to a string; returns a new string

my_string = 'EAS503'
my_string.zfill(8)
'00EAS503'
my_string = '123'
my_string.zfill(8)
'00000123'

3.4.5. Creating a new String#

  • join((value1, value2, value3)) – Creates a new string separating the values by whatever is in the string

years = ('1900', '1924', '1950', '1990')
''.join((years))
'1900192419501990'
years = ('1900', '1924', '1950', '1990')
'-'.join((years))
'1900-1924-1950-1990'
years = ('1900', '1924', '1950', '1990')
', '.join((years))
'1900, 1924, 1950, 1990'
years = ('1900', '1924', '1950', '1990')
print('\n'.join((years)))
1900
1924
1950
1990
  • You can only join strings, you cannot join an integer.

years = ('1900', '1924', '1950', 1990)
', '.join(years)
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
Cell In[29], line 2
      1 years = ('1900', '1924', '1950', 1990)
----> 2 ', '.join(years)

TypeError: sequence item 3: expected str instance, int found