Python String Methods

This notebook is all about working with String.

We will cover some of the builtin string methods in Python

part of #100DaysofCode Python Edition follow along at https://jcutrer.com/100daysofcode

Python Docs Reference: https://docs.python.org/3/whatsnew/2.0.html#string-methods

Some sample data for this excerise.

In [1]:
a = "python"

b = "Today is a good day to start learning python."

mit = """THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, 
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. 
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, 
DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR 
OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
USE OR OTHER DEALINGS IN THE SOFTWARE."""

Python String Methods

In [86]:
len(a) # returns strings length in number of characters
Out[86]:
6
In [4]:
a.upper()
Out[4]:
'PYTHON'
In [5]:
a.lower()
Out[5]:
'python'
In [67]:
b.capitalize()
Out[67]:
'Today is a good day to start learning python.'
In [82]:
a.islower() # testing for all lower case characters
Out[82]:
True
In [85]:
a.isupper() # testing for all upper case characters
Out[85]:
False

str.title() will capitalize each word in a string

In [102]:
mit.title()
Out[102]:
'The Software Is Provided "As Is", Without Warranty Of Any Kind, \nExpress Or Implied, Including But Not Limited To The Warranties Of \nMerchantability, Fitness For A Particular Purpose And Noninfringement. \nIn No Event Shall The Authors Or Copyright Holders Be Liable For Any Claim, \nDamages Or Other Liability, Whether In An Action Of Contract, Tort Or \nOtherwise, Arising From, Out Of Or In Connection With The Software Or The\nUse Or Other Dealings In The Software.'
In [74]:
a.center(80, "=") #pad and center a string
Out[74]:
'=====================================python====================================='

str.count() returns the number of non-overlapping occurrences of substring sub in the range [start, end]. Optional arguments start and end are interpreted as in slice notation.

In [80]:
mit.count('THE') # count the occurences of a substring in a string
Out[80]:
10

str.strip() is equivalent to trim() in some other languages

In [101]:
"         Well Hello There        ".strip()
Out[101]:
'Well Hello There'

str.casefold() is similar to lowercasing but more aggressive because it is intended to remove all case distinctions in a string.

In [103]:
mit.casefold()
Out[103]:
'the software is provided "as is", without warranty of any kind, \nexpress or implied, including but not limited to the warranties of \nmerchantability, fitness for a particular purpose and noninfringement. \nin no event shall the authors or copyright holders be liable for any claim, \ndamages or other liability, whether in an action of contract, tort or \notherwise, arising from, out of or in connection with the software or the\nuse or other dealings in the software.'

String Splitting

In [89]:
weekdays_csv = "monday,tuesday,wednesday,thursday',friday,saturday,sunday"

weekdays_csv.split(",") # returns a list
Out[89]:
['monday', 'tuesday', 'wednesday', "thursday'", 'friday', 'saturday', 'sunday']
In [90]:
mit.splitlines()
Out[90]:
['THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, ',
 'EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF ',
 'MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. ',
 'IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, ',
 'DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR ',
 'OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE',
 'USE OR OTHER DEALINGS IN THE SOFTWARE.']

String Slicing

In [27]:
a[0] + a[-1] # first and last characters
Out[27]:
'pn'
In [44]:
a[:3] # first 3 characters
Out[44]:
'pyt'
In [46]:
b[:-10] # first 10 characters
Out[46]:
'Today is a good day to start learni'
In [47]:
b[-10:] # last 10 characters
Out[47]:
'ng python.'

String Math

In [48]:
a * 5 # multiply a string
Out[48]:
'pythonpythonpythonpythonpython'
In [61]:
a * 5 + b # multiply then add another string
Out[61]:
'pythonpythonpythonpythonpythonToday is a good day to start learning python.'
In [66]:
a / 5  # cannot divide a strings
a - a
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-66-5865f1a73727> in <module>
----> 1 a / 5  # cannot divide a strings
      2 a - a

TypeError: unsupported operand type(s) for /: 'str' and 'int'
In [65]:
b - a # cannot substract strings
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-65-44c137fc1a41> in <module>
----> 1 b - a # cannot substract strings

TypeError: unsupported operand type(s) for -: 'str' and 'str'

This notebook is part of my #100DaysofCode Python Edition project.