Introduction to Linux - A Hands on Guide | Linux Bible | Linux From Scratch | A Newbie's Getting Started Guide to Linux | Linux Command Line Cheat Sheet | More Linux eBooks



Monday, 24 October 2016

Python String Methods - find(), join(), replace(), etc.

Hello readers! This is the 7th article of our Python series 'Python on Terminal' and we will be learning about String Methods in Python in this tutorial. In the previous article on Python Strings, entitled as Python Strings- Creation, Concatenation, Repetition, Indexing and Slicing, we learned to create strings, their concatenation and repetition, their indexing and slicing. This article is the continuum of the mentioned article and this time, we will be exploring Python string methods with examples.

python-string-methods-find-join-replace


The term 'method' might sound unfamiliar to you, if you are a newbie. But no worries, that's why this article is being written. So, a method is a function (in C language context) which when called on an object, returns a value, that might be a modified version of that object or any information related to that. The key difference between functions and methods is that, methods are the functions in a class and are associated with the class objects. Whereas, a function is callable code fragment, which may or may not accept arguments, but is written to avoid redundancy in the code.

As an example, consider a string object mySring. Being an object of a str class, it has a method upper() associated with it. This upper() method is just a function written inside str class and thus, can be used with str class objects only. So, in order to use any method, we have to qualify it with object name as - object_name.method(). Speaking about functions, they are the re-usable piece of code written in the body of the program.

Note : All methods are functions, but vice-versa may not be always true.

Starting our discussion on the string methods, we create a string myString and pass it as an argument to dir() function. When we pass an object to Python built-in dir() function, it provides a list (another Python object, which we will be studying later) of attributes (which will be covered in Object Oriented Programming Concepts), including methods, associated with them (Methods are callable attributes, which can be called on objects).

>>> myString = "CodeNinjaDotIn"

>>> dir(myString)
['__add__', '__class__', '__contains__', '__delattr__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__getslice__', '__gt__', '__hash__', '__init__', '__le__', '__len__', '__lt__', '__mod__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmod__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '_formatter_field_name_split', '_formatter_parser', 'capitalize', 'center', 'count', 'decode', 'encode', 'endswith', 'expandtabs', 'find', 'format', 'index', 'isalnum', 'isalpha', 'isdigit', 'islower', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'partition', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill']

The above list includes some string methods beginning with double underscores, like __contains__, which are called 'Magic Methods' and they are used by Python internally (we will be discussing on this later). Let us have a look at some of the important string methods and see what they do with our Python object MyString.

1. capitalize() Method :

It capitalizes only the first character of the string.
>>> myString = "codeninjadotin"

>>> type(myString.capitalize)
<type 'builtin_function_or_method'>

>>> myString.capitalize()
'Codeninjadotin'

Just for our curiosity, we checked what type the object myString.capitalize belongs to and rightly so, it is a String Method!

2. count() Method :

With this method, we can count number of occurrences of a sub-string (provided as a parameter) in the string on which this method is called.

Syntax: stringName.count(substring, [START], [END]), where in START and END are optional parameters and are indices at which the search begins and ends, respectively.

>>> myString = "CodeNinjaDotIn"

# Search for string 'o' in entire myString
>>> myString.count('o')
2

# Search for string 'o' starting search from index '0' ending (but not including) at index '11'
>>> myString.count('o', 0, 11)
2

# Search for a string 'o' from index '3'
>>> myString.count('o', 3)
2

# Search for a string 'Dot' specified in a variable 'str'
>>> str = 'Dot'
>>> myString.count(str)
1

3. endswith() Method :

This string method accepts a parameter of str type and returns True if the string object (on which this methods is called) ends with the specified string, else returns False.

Syntax: stringName.endswith(substring, [START], [END]), where in START and END are optional parameters (as in case of last example) and are indices at which the search begins and ends, respectively.

>>> myString = "Welcome to CodeNinjaDotIn"

# Check if 'myString' ends with 'Org'
>>> myString.endswith('Org')
False

# Check if 'myString' ends with 'In'
>>> myString.endswith('In')
True

# Check if 'myString[0:9]' ends with 'to'
>>> myString.endswith('to', 0, 9)
False

# Check if 'myString[0:10]' ends with 'to'
>>> myString.endswith('to', 0, 10)
True

# Check if 'myString[5:]' ends with 'In'
>>> myString.endswith('In', 5)
True

4. startswith() Method :

This string method is similar to endswith() methos, it accepts a parameter of str type and returns True if the string object (on which this methods is called) begins with the specified string, else returns False.

Syntax: stringName.startswith(substring, [START], [END]), where in START and END are optional parameters and are indices at which the search begins and ends, respectively.

>>> myString = "Welcome to CodeNinjaDotIn"

# Check if 'myString' begins with 'Wel'
>>> myString.startswith('Wel')
True

# Check if 'myString[10:]' starts with 'Code'
>>> myString.startswith('Code', 10)
False

# Check if 'myString[11:]' starts with 'Code'
>>> myString.startswith('Code', 11)
True

# Check if 'myString[4:17]' starts with 'o'
>>> myString.startswith('o', 4, 17)
True

5. find() Method :

This accepts a parameter of str type and returns index of the sub-string if the string object (on which this methods is called) contains the specified sub-string, else returns -1.

Syntax: stringName.find(substring, [START], [END]), where in START and END are optional parameters and are indices at which the search begins and ends, respectively.

>>> myString = "Welcome to CodeNinjaDotIn"

# Find the index of 'come' if it is in 'myString', else return -1
>>> myString.find('come')
3

# Find the index of 'come' if it is in 'myString[7:]', else return -1
>>> myString.find('come', 7)
-1

# Find the index of 'ja' if it is in 'myString[5:20]', else return -1
>>> myString.find('ja', 5, 20)
18

# Find the index of substring saved in variable 'str', 
# if it is in 'myString', else return -1
>>> str = 'Org'
>>> myString.find(str)
-1

>>> str = 'In'
>>> myString.find(str)
23

6. index() Method :

Similar to find() method, it accepts a parameter of str type and returns index of the sub-string if the string object (on which this methods is called) contains the specified sub-string, the only difference is that it raises an Exception (or an error message, we will study exceptions in separate article) when it doesn't find the sub-string.

Syntax: stringName.index(substring, [START], [END]), where in START and END are optional parameters and are indices at which the search begins and ends, respectively.

>>> myString = "CodeNinjaDotIn"

# Look for index of sub-string 'Nin' in 'myString'
>>> myString.index('Nin')
4

# Look for index of sub-string 'Dot' in 'myString[5:]'
>>> myString.index('Dot', 5)
9

# Look for index of sub-string stored in variable 'str' in 'myString[3:12]'
>>> str = 'ja'
>>> myString.index(str, 3, 12)
7

# Look for index of sub-string 'Net' in 'myString', else raise an Exception
>>> myString.index('Net')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: substring not found

7. isupper() Method :

This method when called on a string object, returns True, if all the letters in that string object are upper-cased, else returns False.

Syntax: stringName.isupper()

>>> myString = "codeninjadotin"
>>> myString.isupper()
False

>>> myString = "CodeNinjaDotIn"
>>> myString.isupper()
False

>>> myString = "CODENINJADOTIN"
>>> myString.isupper()
True

8. islower() Method :

This method when called on a string object, returns True, if all the letters in that string object are lower-cased, else returns False.

Syntax: stringName.islower()

>>> myString = "CODENINJADOTIN"
>>> myString.islower()
False
>>>
>>> myString = "CodeNinjaDotIn"
>>> myString.islower()
False
>>>
>>> myString = "codeninjadotin"
>>> myString.islower()
True

9. isalpha() Method :

This method when called on a string object, returns True, if all the letters in that string object are alphabetic letters, else returns False.

Syntax: stringName.isalpha()

# Below string has a special character
>>> myString = "CodeNinja.In"
>>> myString.isalpha()
False

# Below string has numbers and special characters
>>> myString = "C0d3N1nj@.In"
>>> myString.isalpha()
False

# Below string has only alphabetic characters
>>> myString = "CodeNinjaDotIn"
>>> myString.isalpha()
True

10. isdigit() Method :

This method when called on a string object, returns True, if all the items in that string object are digits, else returns False.

Syntax: stringName.isnum()

>>> myString = "CodeNinja.In"
>>> myString.isdigit()
False

>>> myString = "C0d3N1nj@.In"
>>> myString.isdigit()
False

>>> myString = "567890"
>>> myString.isdigit()
True

11. isalnum() Method :

This method when called on a string object, returns True, if all the items in that string object are alphanumeric characters, else returns False.

Syntax: stringName.isalnum()

>>> myString = "CodeNinja.In"
>>> myString.isalnum()
False

>>> myString = "CodeNinjaDotIn"
>>> myString.isalnum()
True

>>> myString = "C0d3N1nj@.In"
>>> myString.isalnum()
False

>>> myString = "C0d3N1njaD0t1n"
>>> myString.isalnum()
True

12. upper() Method :

This method when called on a string object, converts all the characters in the string object to upper case, this doesn't change the string itself though (as strings are immutable).

Syntax: stringName.upper()

>>> myString = "codeninjadotin"
>>> myString.upper()
'CODENINJADOTIN'

>>> myString = "CodeNinjaDotIn"
>>> myString.upper()
'CODENINJADOTIN'

>>> myString = "C0d3N1njaD0t1n"
>>> myString.upper()
'C0D3N1NJAD0T1N'

13. lower() Method :

This method when called on a string object, converts all the characters in the string object to lower case, this doesn't change the string itself though (as strings are immutable).

Syntax: stringName.lower()

>>> myString = "CodeNinjaDotIn"
>>> myString.lower()
'codeninjadotin'

# Strings are Immutable :)
>>> myString
'CodeNinjaDotIn'

>>> myString = "C0d3N1njaD0t1n"
>>> myString.lower()
'c0d3n1njad0t1n'

14. title() Method :

This method when called on a string object, converts first letter of each word in the string object to upper case, this doesn't change the string itself though (as strings are immutable).

Syntax: stringName.title()

>>> myString = "code ninja dot in"
>>> myString.title()
'Code Ninja Dot In'

# Strings are Immutable
>>> myString
'code ninja dot in'

15. swapcase() Method :

This method when called on a string object, returns a string with all upper cased letters to lower case and vice versa as in the string object.

Syntax: stringName.swapcase()

>>> myString = "codeninjadotin"
>>> myString.swapcase()
'CODENINJADOTIN'

>>> myString = "CODENINJADOTIN"
>>> myString.swapcase()
'codeninjadotin'

>>> myString = "CodeNinjaDotIn"
>>> myString.swapcase()
'cODEnINJAdOTiN'

17. join() Method :

This method takes one argument - a sequence, and it is called on a str type, that acts as a separator. With this, join() method joins the strings in the sequence in the argument with the separator to create and return a string. A sequence can be a list type or a tuple type or any iterable/sequence, while separator has to be a str type. Please take a look at below examples if this sounds confusing.

Syntax: <separator>.join(<sequence/iterable>)

>>> print ":".join(["00", "11", "22", "33", "44"])
00:11:22:33:44

# A List as a sequence
>>> mySequence = ["00", "11", "22", "33", "44"]
>>> print "-".join(mySequence)
00-11-22-33-44

# Sequence stored in a variable
>>> mySep = '-*-'
>>> mySep.join(mySequence)
'00-*-11-*-22-*-33-*-44'

# A Tuple as a sequence
>>> mySequence = ('Happy', 'Birthday')
>>> mySep.join(mySequence)
'Happy-*-Birthday'


18. replace() Method :

This method accepts two mandatory parameters- SUBSTRING and REPLACEMENT and one optional parameter- COUNT. What this method does is, it replaces SUBSTRING in the string object, on which the method is called, with the REPLACEMENT string, while COUNT denotes the maximum number of replacements to be made, which defaults to 'all' (replacing all the instances of SUBSTRING).

Syntax: stringName.replace(SUBSTRING, REPLACEMENT, [COUNT])

>>> myString = "this is the end"
>>> myString.replace('is', 'at')
'that at the end'

>>> myString.replace('is', 'at', 1)
'that is the end'

>>> subStr = 'is'
>>> repStr = 'at'
>>> myString.replace(subStr, repStr)
'that at the end'

And indeed, we have reached at the end of this article. We have studied bunch of string methods and worked on them, we have not covered all of them though. But, I'm sure that, we will be covering most of them as we progress through the tutorial series. Thanks for stopping by and reading this article, please share your opinions & feedback in the comment section below and do stay connected.

This article is originally published at www.codeninja.in - Introduction to Python String Methods

0 comments:

Post a Comment