Strings in Python are represented using the built-in str type/class. This class defines methods which can be used to manipulate or extract information from string instances. The string methods can be divided  into:

  1. Searching Methods
  2. Manipulation Methods
  3. Validation Methods 
  4. Formatting Methods
  5. Encoding and Decoding Methods

Searching Methods

These methods are used to determine if a given pattern is a substring in a string.  All of these methods are case sensitive.

find():

Syntax:

S.find(pattern)

This method returns the beginning index  of the leftmost  occurrence of the pattern in the string S.

Examples:

"Hello, World!".find('e')
//1
"Hello, World!".find("World")
//7
"And Then There Were None".find("None")
//20

-1 is returned if the given pattern does not occur in the string.

"Hello, World!".find("j")
//-1
"Hello, World!".find('world')
//-1

index():

Syntax:

S.index(pattern)

This method is similar to find() except that, if the pattern does not occur in the string, a ValueError is raised. It returns the starting index of the leftmost occurrence of the pattern in the string S.

Examples:

"Hello, World!".index('l')
//2
"Hello, World!".index('World!')
//7
"And Then There Were None.".index('None')
//20
"And Then There Were None.".index('All')
//ValueError: substring not found

rfind():

Syntax:

S.rfind(pattern)

This method returns the beginning index of the  rightmost  occurrence of the pattern in the string S. It returns -1 if the pattern does not occur in the string.

Examples:

"Hello, World!".rfind('l')
//10
"Hello, World!".rfind('o')
//8
"Hello, World!".rfind('f')
//-1

rindex():

Syntax:

S.rindex(pattern)

This method is similar to rfind(), but raises a  ValueError if the pattern does not occur in the string S. 

Examples:

"Hello, World!".rindex('o')
//8
"Hello,World!".rindex('World')
//6
"Hello, World!".rindex('world')
//ValueError: substring not found

count():

Syntax:

S.count(pattern)

This method returns the number of non-overlapping times that the pattern occurs in the string S.

Examples:

"Hello, World!".count('l')
//3
"Hello, World!".count('World')
//1
"Hello, World!".count('j')
//0
"aaaaaaaa".count('aa')
//4

 

The Searching  methods also takes two  optional arguments, start and stop . These arguments effectively restricts the search to the slice S[start : stop], where S is the string. The syntax is:

S.method(pattern, start, stop)

If the stop is not given, the search goes on up to the end of the string.

Examples:

"And Then There Was None.".find("And", 5)
//-1
"Hello, World!".count("H",3)
//0
"Hello, World!".index('o', 5, 10)
//8

 

Manipulation Methods

These methods are used to construct strings related to the given string. Since strings are immutable, none of these method modifies the original string, they instead return an entirely new string that is closely related to the original one.

replace():

Syntax:

S.replace(old, new)

Returns a new copy of string S with all occurrences of old replaced with new .

Examples:

"Hello, World!".replace('World', 'Python')
//'Hello, Python!'
"And Then There Were None.".replace('Were', 'Was')
//'And Then There Was None.'
"aaaaaaa".replace('a', 'b')
//'bbbbbbb'

capitalize():

Syntax:

S.capitalize()

Returns a new copy of string S with the first character being uppercase and all the subsequent alphabetical characters being lower case.

Examples:

"Hello, World!".capitalize()
//'Hello, world!'
"HELLO, WORLD!".capitalize()
//'Hello, world!'
"And Then There Were None.".capitalize()
//'And then there were none.'

upper():

Syntax:

S.upper()

Returns a copy of string S with all the alphabetical characters being uppercase.

Examples:

"Hello, World!".upper()
//'HELLO, WORLD!'
"And Then There Were None.".upper()
//'AND THEN THERE WERE NONE.'

lower():

Syntax:

S.lower()

Returns a new copy of S with all the alphabetical characters being lowercase.

Examples:

"Hello, World!".lower()
//'hello, world!'
"And Then There Was None.".lower()
//'and then there was none.'

strip():

Syntax:

S.strip()

Returns a new copy of S with all the leading and trailing spaces removed.

Examples:

"  Hello, World!   ".strip()
//'Hello, World!'

lstrip():

Syntax:

S.lstrip()

Returns a new copy of string S with leading spaces removed.

Example:

"    Hello, World!  ".lstrip()
//'Hello, World!  '

rstrip():

Syntax:

S.rstrip()

Returns a new copy of string S with trailing spaces removed. 

Example:

"  Hello, World!       ".rstrip()
//'  Hello, World!'

join():

Syntax:

(sep).join(S)

Return the composition of the given sequence of strings, inserting sep as delimiter between each pair.

Examples:

" ".join("Hello World!")
//'H e l l o   W o r l d !
",".join("Hello World!")
//'H,e,l,l,o, ,W,o,r,l,d,!'

The join method  is also used to form a string from other compatible types which are built with strings fragments, for example to form a string from a list of characters, we can use an empty string as sep. Example:

''.join(['H', 'e', 'l', 'l', 'o', ',', ' ', 'W', 'o', 'r', 'l', 'd', '!'])
//'Hello, World!'

splitlines():

Syntax:

S.splitlines()

Return a list of substrings of S, as delimited by newlines.

Examples:

"Hello\nWorld!".splitlines()
//['Hello', 'World!']
"And\nThen\nThere\nWere\nNone.".splitlines()
//['And', 'Then', 'There', 'Were', 'None.']

split():

Syntax:

S.split(sep, count)

Return a list of substrings of S, as delimited by the first count occurrences of sep. If count is not specified, split on all occurrences. If sep is not specified, use whitespace as delimiter.

Example:

"Hello, World!".split(',')
//['Hello', ' World!']
"And Then There Were None.".split()
//['And', 'Then', 'There', 'Were', 'None.']

rsplit():

Syntax:

S.rsplit(sep, count)

Similar to split, but using the rightmost occurrences of sep.

Examples:

"Hello, World!".rsplit('r',1)
//['Hello, Wo', 'ld!']
"And Then There Were None.".rsplit(" ", 2)
//['And Then There', 'Were', 'None.']

partition():

Syntax:

S.partition(sep)

Returns (head, sep, tail) such that S = head + sep + tail, using leftmost occurrence of sep, if any; else return (S,'' ,'' )

Examples:

"Hello, World!".partition(',')
//('Hello', ',', ' World!')
"Hello, World!".partition('l')
//('He', 'l', 'lo, World!')

rpartition():

Syntax:

S.rpartition(sep)

Return (head, sep, tail) such that S = head + sep + tail, using rightmost occurrence of sep, if any; else return ( '', '', s)

Examples:

"Hello, World!".rpartition('j')
//('', '', 'Hello, World!')
"Hello, World!".rpartition('l')
//('Hello, Wor', 'l', 'd!')

swapcase():

Syntax:

S.swapcase()

Returns a copy of the string S, but  with all the upper case letters lowercased and vice versa.

Examples:

"Hello, World!".swapcase()
//'hELLO, wORLD!'
"And Then There Were None.".swapcase()
//'aND tHEN tHERE wERE nONE.'

 

Validation Methods

These methods are used to test a boolean property of a string,  such as whether it begins or ends with a given pattern. These methods returns a boolean value i.e either True or False.

startswith():

Syntax:

S.startswith(pattern)

Returns True if the string S starts with the given pattern,. else False.

Examples:

"Hello, World!".startswith('Hello')
//True
"Hello, World!".startswith('World!')
//False
"And Then There Was None.".startswith('and')
//False
"And Then There Was None.".startswith('And')
//True

endswith():

Syntax:

S.endswith(pattern)

Returns True if the string S ends with the given pattern, else False.

Examples:

"Hello, World!".endswith('World!')
//True
"Hello, World!".endswith('Hello')
//False
"And Then There Were None.".endswith('None')
//False
"And Then There Were None.".endswith('None.')
//True

isspace():

Syntax:

S.isspace()

Returns True if all the characters of a non-empty string S are white spaces, else False.

Examples:

"Hello, World!".isspace()
//False
"".isspace()
//False
"    ".isspace()
//True

isalpha():

Syntax:

S.isalpha()

Returns True if all the characters of a non-empty string S are alphabetic, else False.  Alphabetic characters are uppercase  A-Z  and lowercase  a-z.

Examples:

"Hello, World!".isalpha()
//False
"Hello, World".isalpha()
//True

islower():

Syntax:

S.islower()

Returns True if the string S  contains one or more alphabetic characters, all of which are lowercased .

Examples:

"Hello, World!".islower()
//False
"hello, world!".islower()
//True

isupper():

Syntax:

S.isupper()

Returns True if the string S is made up of one or more alphabetic characters, all of which are uppercased.

Examples:

"Hello, World!".isupper()
//False
"HELLO, WORLD!".isupper()
//True

isdigit():

Syntax

S.isdigit()

Returns True if all the characters of string S are digits, else False .

Examples:

" 123456".isdigit()
//False
"123456".isdigit()
//True

isnumeric():

Syntax:

S.isnumeric()
Return True if all characters of nonempty string are numeric Unicode characters (e.g., 0–9, equivalents, fraction characters)

Examples:

"67".isnumeric()
//True

isalnum():

Syntax:

S.isalnum()

Return True if all characters of nonempty string are either alphabetic or numeric.

Examples:

"python234".isalnum()
//True

isidentifier():

Syntax:

S.isidentifier()

Returns True if the string S is a valid identifier, else False. A string is considered a valid identifier if it only contains alphanumeric letters (a-z) and (0-9), or underscores (_). A valid identifier cannot start with a number, or contain any spaces. 

Examples:

"age".isidentifier()
//True
"first_name".isidentifier()
//True
"2nd_name".isidentifier()
//False

istitle():

Syntax:

S.istitle()

The istitle() method returns True if all words in a text start with a upper case letter, and the rest characters of the word are all lower case, otherwise False.

Numbers and special characters are ignored.

Examples:

"Hello, World!".istitle()
//True
"And Then There Were None.".istitle()
//True
"HELLO, WORLD!".istitle()
//False
"Hello, WorlD!".istitle()
//False

isprintable():

Syntax:

S.isprintable()

The isprintable() method returns True if all the characters are printable, otherwise False.

Examples:

"Hello, World!".isprintable()
//True
"Hell,\nWorld!".isprintable()
//False

 

Formatting Method

The format() method is used in formatting a string. It is used to substitute values in a string either by position or by name.

Syntax:

S.format(*args, **kwargs)

Curly braces {} are used as placeholders inside the string to designate positions where the substitute values will  be positioned.

Examples of formatting with positional arguments:

"{}, World!".format('Hello')
//'Hello, World!'
"{} Then There {} {}.".format('And','Were','None')
//'And Then There Were None.'

Positions can be put inside the curly braces to alter the order of substitution. as shown below:

"{1} Then There {2} {0}.".format('None','And','Were')
//'And Then There Were None.'

Example of formatting with keyword arguments:

"{x}, World!".format(x='Hello')
//'Hello, World!'
"{a} Then There {b} {c}.".format(a = 'And', b = 'Were', c = 'None')
//'And Then There Were None.'
"{c} Then There {b} {a}.".format(a = 'None', b = 'Were', c = 'And')
//'And Then There Were None.'