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.

ExampleEdit & Run
S = "Hello, World!"

print( S.find('e') )

print( S.find("World") )

print( S.find('d') )
Output:
1711[Finished in 0.010495551163330674s]

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

ExampleEdit & Run
S = "Hello, World!"

print( S.find("j") )
print( S.find('hello') )
Output:
-1-1[Finished in 0.010140927042812109s]

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.

ExampleEdit & Run
S = "Hello, World!"
print( S.index('l') ) #2
print( S.index('World!') ) #7

S = "And Then There Were None."
print( S.index('None') ) #20
print( S.index('All') ) #ValueError
Output:
2720Traceback (most recent call last):  File "<string>", line 7, in <module>ValueError: substring not found[Finished in 0.009790909010916948s]

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.

ExampleEdit & Run
S = "Hello, World!"

print( S.rfind('l') ) #10

print( S.rfind('o') ) #8

print( S.rfind('f') ) #-1
Output:
108-1[Finished in 0.009542224928736687s]

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. 

ExampleEdit & Run
S = "Hello, World!"

print( S.rindex('o') ) #8

print( S.rindex('World') ) #6

print( S.rindex('world') ) #ValueError
Output:
87Traceback (most recent call last):  File "<string>", line 7, in <module>ValueError: substring not found[Finished in 0.009255469078198075s]

count()

Syntax:

S.count(pattern)

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

ExampleEdit & Run
S = "Hello, World!"
print( S.count('l') ) #3
print( S.count('World') ) #1
print( S.count('j') ) #0

S = "aaaaaaaa"
print( S.count('aa') ) #4
Output:
3104[Finished in 0.009920967044308782s]

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.

ExampleEdit & Run
S = "And Then There Was None."
print( S.find("And", 5) ) #-1

S = "Hello, World!"
print( S.count("H", 3) ) #0
print( S.index('o', 5, 10) ) #8
Output:
-108[Finished in 0.009717646986246109s]

Manipulation Methods

These methods are used to construct strings related to another 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 .

ExampleEdit & Run
S = "Hello, World!"
result = S.replace('World', 'Python')
print( result )

S = "And Then There Were None."
result = S.replace('Were', 'Was')
print( result )

S = "aaaaaaa"
result = S.replace('a', 'b')
print( result )
Output:
Hello, Python!And Then There Was None.bbbbbbb[Finished in 0.009796838974580169s]

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.

ExampleEdit & Run
S = "Hello, World!"
result = S.capitalize()
print( result )

S = "HELLO, WORLD!"
result = S.capitalize()
print( result )

S = "And Then There Were None."
result = S.capitalize()
print( result )
Output:
Hello, world!Hello, world!And then there were none.[Finished in 0.009821194922551513s]

upper()

Syntax:

S.upper()

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

ExampleEdit & Run
S = "Hello, World!"
result = S.upper()
print( result )

S = "And Then There Were None."
result = S.upper()
print( result )
Output:
HELLO, WORLD!AND THEN THERE WERE NONE.[Finished in 0.009672790067270398s]

lower()

Syntax:

S.lower()

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

ExampleEdit & Run
S = "Hello, World!"
result = S.lower()
print( result )

S = "And Then There Was None."
result = S.lower()
print( result )
Output:
hello, world!and then there was none.[Finished in 0.00961861596442759s]

strip()

Syntax:

S.strip()

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

ExampleEdit & Run
S = "   Hello, World!   "

result = S.strip()

print( result )
Output:
Hello, World![Finished in 0.009471497032791376s]

lstrip()

Syntax:

S.lstrip()

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

ExampleEdit & Run
S = "    Hello, World!   "

result = S.lstrip()

print( result )
Output:
Hello, World!   [Finished in 0.0093966128770262s]

rstrip()

Syntax:

S.rstrip()

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

ExampleEdit & Run
S = "  Hello, World!       "

result = S.rstrip()

print( result )
Output:
  Hello, World![Finished in 0.009686419973149896s]

join()

Syntax:

(sep).join(S)

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

ExampleEdit & Run
print( "  ".join("Hello World!") )
print( ",".join("Hello World!") )
Output:
H  e  l  l  o     W  o  r  l  d  !H,e,l,l,o, ,W,o,r,l,d,![Finished in 0.00932510499842465s]

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.

ExampleEdit & Run
L = ['H', 'e', 'l', 'l', 'o', ',', ' ', 'W', 'o', 'r', 'l', 'd', '!']

print( ''.join(L) )
Output:
Hello, World![Finished in 0.010044271824881434s]

splitlines()

Syntax:

S.splitlines()

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

ExampleEdit & Run
S = "Hello\nWorld!"
result = S.splitlines()
print( result )

S = "And\nThen\nThere\nWere\nNone."
result = S.splitlines()
print( result )
Output:
['Hello', 'World!']['And', 'Then', 'There', 'Were', 'None.'][Finished in 0.010041700210422277s]

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.

ExampleEdit & Run
S = "Hello, World!"
result = S.split(',')
print( result )

S = "And Then There Were None."
result = S.split()
print( result )
Output:
['Hello', ' World!']['And', 'Then', 'There', 'Were', 'None.'][Finished in 0.009896846022456884s]

rsplit()

Syntax:

S.rsplit(sep, count)

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

ExampleEdit & Run
S = "Hello, World!"
result = S.rsplit('r',1)
print( result )

S = "And Then There Were None."
result = S.rsplit(" ", 2)
print( result )
Output:
['Hello, Wo', 'ld!']['And Then There', 'Were', 'None.'][Finished in 0.009328854037448764s]

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,'' ,'' )

ExampleEdit & Run
S = "Hello, World!"

print( S.partition(',') )

print( S.partition('l') )
Output:
('Hello', ',', ' World!')('He', 'l', 'lo, World!')[Finished in 0.009763500886037946s]

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)

ExampleEdit & Run
S = "Hello, World!"

print( S.rpartition('j') )

print( S.rpartition('l') )
Output:
('', '', 'Hello, World!')('Hello, Wor', 'l', 'd!')[Finished in 0.00974442483857274s]

swapcase()

Syntax:

S.swapcase()

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

ExampleEdit & Run
S = "Hello, World!"
result = S.swapcase()
print( result )

S = "And Then There Were None."
result = S.swapcase()
print( result )
Output:
hELLO, wORLD!aND tHEN tHERE wERE nONE.[Finished in 0.009948630817234516s]

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.

ExampleEdit & Run
S = "Hello, World!"
print( S.startswith('Hello') )
print( S.startswith('World!') )

S = "And Then There Was None."
print( S.startswith('and') )
print( S.startswith('And') )
Output:
TrueFalseFalseTrue[Finished in 0.009796671103686094s]

endswith()

Syntax:

S.endswith(pattern)

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

ExampleEdit & Run
S = "Hello, World!"
print( S.endswith('World!') ) #True
print( S.endswith('Hello') ) #False

S = "And Then There Were None."
print( S.endswith('None') ) #False
print( S.endswith('None.') ) #True
Output:
TrueFalseFalseTrue[Finished in 0.00950905098579824s]

isspace()

Syntax:

S.isspace()

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

ExampleEdit & Run
print( "Hello, World!".isspace() ) #False

print( "".isspace() ) #False

print( "    ".isspace() ) #True
Output:
FalseFalseTrue[Finished in 0.009381287032738328s]

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.

ExampleEdit & Run
print( "Hello, World".isalpha() )#True

print( "Hello, World!!".isalpha() )#False
Output:
FalseFalse[Finished in 0.009366501122713089s]

islower()

Syntax:

S.islower()

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

ExampleEdit & Run
S = "Hello, World!"
print( S.islower() )

S = "hello, world!"
print( S.islower() )
Output:
FalseTrue[Finished in 0.009739476023241878s]

isupper()

Syntax:

S.isupper()

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

ExampleEdit & Run
S = "Hello, World!"
print( S.isupper() )

S = "HELLO, WORLD!"
print( S.isupper() )
Output:
FalseTrue[Finished in 0.009882396087050438s]

isdigit()

Syntax

S.isdigit()

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

ExampleEdit & Run
print( " 123456".isdigit() ) #False

print( "123456".isdigit() ) #True
Output:
FalseTrue[Finished in 0.009774959180504084s]

isnumeric()

Syntax:

S.isnumeric()
Return True if all characters of nonempty string are numeric Unicode characters (e.g., 0–9, equivalents, fraction characters)
ExampleEdit & Run
print( "67".isnumeric() )
Output:
True[Finished in 0.009946735110133886s]

isalnum()

Syntax:

S.isalnum()

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

ExampleEdit & Run
print( "python234".isalnum() )
Output:
True[Finished in 0.00966036505997181s]

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. 

ExampleEdit & Run
print( "age".isidentifier() )

print( "first_name".isidentifier() )

print( "2nd_name".isidentifier() )
Output:
TrueTrueFalse[Finished in 0.009552517905831337s]

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.

ExampleEdit & Run
print( "Hello, World!".istitle() )

print( "And Then There Were None.".istitle() )

print( "HELLO, WORLD!".istitle() )

print( "Hello, WorlD!".istitle() )
Output:
TrueTrueFalseFalse[Finished in 0.009910281049087644s]

isprintable()

Syntax:

S.isprintable()

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

ExampleEdit & Run
print( "Hello, World!".isprintable() )

print( "Hell,\nWorld!".isprintable() )
Output:
TrueFalse[Finished in 0.009758703177794814s]

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:

ExampleEdit & Run
S = "{}, World!"
print( S.format('Hello') )

S = "{} Then There {} {}."
print( S.format('And','Were','None') )
Output:
Hello, World!And Then There Were None.[Finished in 0.010029916884377599s]

Positions can be put inside the curly braces to alter the order of substitution. 

ExampleEdit & Run
S = "{1} Then There {2} {0}."

print( S.format('None','And','Were') )
Output:
And Then There Were None.[Finished in 0.009834586177021265s]

Example of formatting with keyword arguments:

ExampleEdit & Run
S = "{x}, World!"
print( S.format(x='Hello') )

S = "{a} Then There {b} {c}."
print( S.format(a = 'And', b = 'Were', c = 'None') )

S = "{c} Then There {b} {a}."
print( S.format(a = 'None', b = 'Were', c = 'And') )
Output:
Hello, World!And Then There Were None.And Then There Were None.[Finished in 0.009769791970029473s]