Functions of Strings in Python

Strings: Any combination of characters or text written in single, double, or triple quotes are treated as strings. Internally strings are stored in single quotes. Example:

#string of lowercase and uppercase alphabets
string1=”Gargs Academy”

#string of alphanumeric characters ie alphabets and digits
string2=”Phone no 9467863365″

#empty String
string3=””

Creating Strings by directly assigning string literals: We can create both empty strings as well as non empty strings by
1) directly assigning the string values or
2) using the built in method str() of python.

Creating Empty Strings by directly assigning empty string literals: We can assign empty strings enclosed in single, double or triple quotes as:

>>> string1=''
>>> string1
''

>>> string2=""
>>> string2
''

>>> string3=''''''
>>> string3
''

>>> string4=""""""
>>> string94
''

Creating Non- Empty Strings by directly assigning string literals: We can assign any string enclosed in single, double or triple quotes as:

>>> str1='gargs academy'
>>> str1
'gargs academy'

>>> str2="gargs academy"
>>> str2
'gargs academy'

Triple quotes ”’ and “”” are used for multi line strings.

>>> str1="""gargs
academy"""
>>> str1
'gargs\nacademy'

>>> str2='''gargs
academy'''
>>> str2
'gargs\nacademy'

For multi line strings, statement continuation mark \ is used. If we want space in between the strings, we must give space explicitly.

>>> str1="""gargs\
academy"""
>>> str1
'gargsacademy'

>>> str2="""gargs \      #notice the blank space after s and before \
academy"""
>>> str2
'gargs academy'

Creating Strings by using str() method: We can create both empty strings as well as non empty strings by str() method.

Creating Empty Strings using str() method : We can create empty string using str() method in various ways as

>>> string1=str()
>>> string1
''

>>> string2=str("")
>>> string2
''

>>> string3=str('')
>>> string3
''

>>> string4=str("""""")
>>> string4
''

>>> string5=str('''''')
>>> string5
''

Creating Non Empty Strings using str() method : We can create non empty string using str() method in various ways as

>>> string1=str("gargs academy")
>>> string1
'gargs academy'

>>> string2=str('gargs academy')
>>> string2
'gargs academy'

>>> string3=str('''gargs academy''')
>>> string3
'gargs academy'

>>> string4=str("""gargs academy""")
>>> string4
'gargs academy'

>>> string5=str("""gargs
academy""")
>>> string5
'gargs\nacademy'

>>> string6=str('''gargs
academy''')
>>> string6
'gargs\nacademy'

>>> string7=str('''gargs\
academy''')
>>> string7
'gargsacademy'

>>> string8=str("""gargs\
academy""")
>>> string8
'gargsacademy'

Mutable: Strings are immutable objects ie. once created, we can’t change individual characters of the strings.

>>> string1="gargs academy"
>>> string1
'gargs academy'

>>> string1[3]='P'
Traceback (most recent call last):
  File "<pyshell#45>", line 1, in <module>
    string1[3]='P'
TypeError: 'str' object does not support item assignment

Indexing on Python Strings: We can access any character using its index as:
stringname[valid_index]
Python supports 2-way indexing on strings: Forward Indexing and Backward Indexing.

Forward Indexing: In it, characters of a string are indexed from 0 to n-1 where n is the number of characters in the string.

>>> string1="gargs academy"
>>> string1
'gargs academy'

>>> string1[2]
'r'
>>> string1[7]
'c'

If the index does not exist, then an error message is shown as:

>>> string1="gargs academy"
>>> string1
'gargs academy'

>>> string1[20]
Traceback (most recent call last):
  File "<pyshell#48>", line 1, in <module>
    string1[20]
IndexError: string index out of range

Backward Indexing: In it, characters of a string are indexed from right side using negative indexes ie -1, -2, -3 and so on upto -n where n is the number of characters in the string.

>>> string1="gargs academy"

>>> string1[-2]
'm'
>>> string1[-7]
'a'

If the index does not exist, then an error message is shown as:

>>> string1="gargs academy"

>>> string1[-20]
Traceback (most recent call last):
  File "<pyshell#53>", line 1, in <module>
    string1[-20]
IndexError: string index out of range

String Operations: There are 6 types of operations possible on Strings.
1. Concatenations
2. Repetition
3. Membership
4. Slicing
5. Traversing Strings
6. Deleting Strings

Concatenation/ Merging/Joining two strings: We can join two strings as:
stringname1 + stringname2

>>> string1="gargs"
>>> string2="academy"

>>> string1 + string2
'gargsacademy'

>>> string2 + string1
'academygargs'

Elements of both the strings will appear in the order, in which strings are written i.e string1 + string2 will display elements of string1 before elements of string2 but string2 + string1 will display elements of string2 before elements of string1

>>> string1 + string2
'gargsacademy'

>>> string2 + string1
'academygargs'

We can concatenate only a string with another string, otherwise python will report an error as:

>>> string1="gargs academy"

>>> string1 + 9467863365
Traceback (most recent call last):
  File "<pyshell#60>", line 1, in <module>
    string1 + 9467863365
TypeError: can only concatenate str (not "int") to str

Repetition: We can replicate or repeat the string multiple(n) times as:
1) n * stringname
2) stringname *n

>>> string1="gargs academy"

>>> string1 * 2
'gargs academygargs academy'

>>> string1 * 3
'gargs academygargs academygargs academy'

To repeat or replicate the strings, we can also write as:

>>> string1="gargs academy"

>>> 2 * string1
'gargs academygargs academy'

>>> 3 * string1
'gargs academygargs academygargs academy'

Membership on Strings: In Python, there are two membership operators. (in, not in), which are used to test whether or not the character or string is present in the given string.
1) item in stringname
2)item not in stringname

>>> string1="gargs academy"

>>> "gargs" in string1
True
>>> "Guptas" in string1
False

>>> "gargs" not in string1
False
>>> "Guptas" not in string1
True

in operator returns True only if the string is present in the given string with matching case because uppercase and lowercase letters are stored and treated differently.

>>> string1="gargs academy"

>>> "gargs" in string1
True

>>> "Gargs" in string1
False

>>> "gargs" not in string1
False

>>> "Gargs" not in string1
True

Slicing the strings: To access a range of characters from a string, we can extract a part/slice of the string as:
stringname[initial : final : step]
It will extract a part of the string from initial position upto final position (final position not included), in given step size.
default value of initial is 0, default value of final is n and default value of size is 1

>>> string1="gargs academy"

>>> string1[2:6:1]             #starting from 2 upto 6 in steps of 1
'rgs '

>>> string1[2:6]               #starting from 2 upto 6 in default steps i.e. 1
'rgs '

>>> string1[2:6:2]             #starting from 2 upto 6 in steps of 2
'rs'

>>> string1[0:]                #starting from 0 upto default ie n=7 in default steps ie 1
'gargs academy'

>>> string1[:]                 #starting from default ie 0 upto default ie n=7 in default steps ie 1
'gargs academy'

>>> string1[:7]                #starting from default ie 0 upto 7 in default steps ie 1
'gargs a'

>>> string1[:70]               #starting from default ie 0 upto 10 in default steps ie 1
'gargs academy'

>>> string1[::]                #starting from default ie 0 upto default ie n=7 in default steps ie 1
'gargs academy'

>>> string1[::-1]              #starting from default ie 0 upto default ie n=7 in steps ie -1            
 'ymedaca sgrag'               #notice the list is reversed

>>> string1[]                  #atleast a : is necessary 
SyntaxError: invalid syntax    #even if you dont specify any initial, final or step value
                               #otherwise error message will be shown as

Traversing a string using loops: We can traverse (ie. access or print or perform any other operation on each individual character of the string exactly once) using loops as:

>>> string1="gargs academy"
>>> for ch in string1:
	print(ch)

	
g
a
r
g
s
 
a
c
a
d
e
m
y

Deleting Strings: After deleting the string, we will no longer be able to use the string.
We can delete the string ie remove it from the memory as
del stringname

>>> string1="gargsacademy"
>>> string1
'gargsacademy'

>>> del string1
>>> string1
Traceback (most recent call last):
  File "<pyshell#26>", line 1, in <module>
    string1
NameError: name 'string1' is not defined

Applying built in functions on Strings in Python: Built in functions are predefined functions in python that are available for use without the need for importing any module. We can apply various built in functions on strings such as len(), str(), type(), id(),sorted(), del() etc.

len() is used to find the number of characters in the string.

>>> string1="gargsacademy"
>>> len(string1)
12

>>>#space accounts for 1 character
>>> string2="gargs academy"
>>> len(string2)
13

>>>#escape sequences counted as a single character eg \' is a single character
>>> string3="garg\'s academy"
>>> string3
"garg's academy"
>>> len(string3)
14

>>>#when we press enter, it is a newline character \n and counted as a single character.
>>> string4="""gargs
academy"""
>>> string4
'gargs\nacademy'
>>> len(string4)
13

>>>#\ is treated as statement continuation mark, not as a character here.
>>> string5="""gargs\
academy"""
>>> string5
'gargsacademy'
>>> len(string5)
12

str() : It is used to create strings.

>>> string1=str()
>>> string1
''

>>> string2=str("")
>>> string2
''

>>> string3=str('''gargs academy''')
>>> string3
'gargs academy'

>>> string4=str("""gargs academy""")
>>> string4
'gargs academy'

>>> string5=str("""gargs
academy""")
>>> string5
'gargs\nacademy'

>>> string6=str('''gargs
academy''')
>>> string6
'gargs\nacademy'

>>> string7=str('''gargs\
academy''')
>>> string7
'gargsacademy'

>>> string8=str("""gargs\
academy""")
>>> string8
'gargsacademy'

type() is used to find the data type of the object passed as an argument.

>>> string1="gargsacademy"
>>> string1
'gargsacademy'

>>> type(string1)
<class 'str'>

id() is used to find the address or location where the first character of the string is stored in memory.

>>> string1="gargs academy"
>>> string1
'gargs academy'

>>> id(string1)
2627724057904

sorted(): It is used to create a string from the characters of a given string in sorted order.

>>> string1="gargs academy"
>>> sorted(string1)
[' ','a', 'a', 'a', 'c', 'd', 'e', 'g', 'g', 'm', 'r', 's', 'y']

We can also store the result in another string variable as:

>>> string1="gargs academy"
>>> string1
'gargs academy'

>>> string2=sorted(string1)
>>> string2
[' ', 'a', 'a', 'a', 'c', 'd', 'e', 'g', 'g', 'm', 'r', 's', 'y']

But the original string remains unchanged.

>>> string1="gargs academy"
>>> string1
'gargs academy'

>>> string2=sorted(string1)
>>> string2
[' ', 'a', 'a', 'a', 'c', 'd', 'e', 'g', 'g', 'm', 'r', 's', 'y']

>>> string1
'gargs academy'

Del(): It is used to delete the strings. After deleting the string, we will no longer be able to use the string.
We can delete the string ie remove it from the memory as
del (stringname)

>>> string1="gargsacademy"
>>> string1
'gargsacademy'

>>> del(string1)

>>> string1
Traceback (most recent call last):
  File "<pyshell#103>", line 1, in <module>
    string1
NameError: name 'string1' is not defined

Since strings are immutable, we can’t delete individual characters of a string

>>> string1="gargsacademy"
>>> string1
'gargsacademy'

>>> del(string1[3])
Traceback (most recent call last):
  File "<pyshell#106>", line 1, in <module>
    del(string1[3])
TypeError: 'str' object doesn't support item deletion

String Functions in Python: We can apply various functions on Strings such as:

  1. capitalize()
  2. title()
  3. lower()
  4. upper()
  5. count()
  6. find()
  7. index()
  8. endswith()
  9. startswith()
  10. isalnum()
  11. isalpha()
  12. isdigit()
  13. islower()
  14. isupper()
  15. isspace()
  16. lstrip()
  17. rstrip()
  18. strip()
  19. replace()
  20. join()
  21. partition()
  22. split()

To see a list of all functions of a string:

>>> dir(str)

['__add__', '__class__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mod__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmod__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'capitalize', 'casefold', 'center', 'count', 'encode', 'endswith', 'expandtabs', 'find', 'format', 'format_map', 'index', 'isalnum', 'isalpha', 'isascii', 'isdecimal', 'isdigit', 'isidentifier', 'islower', 'isnumeric', 'isprintable', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'maketrans', 'partition', 'removeprefix', 'removesuffix', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill']

To see a description of all the functions of the string:

>>> help(str)

Help on class str in module builtins:

class str(object)
 |  str(object='') -> str
 |  str(bytes_or_buffer[, encoding[, errors]]) -> str
 |  
 |  Create a new string object from the given object. If encoding or
 |  errors is specified, then the object must expose a data buffer
 |  that will be decoded using the given encoding and error handler.
 |  Otherwise, returns the result of object.__str__() (if defined)
 |  or repr(object).
 |  encoding defaults to sys.getdefaultencoding().
 |  errors defaults to 'strict'.
 |  
 |  Methods defined here:
 |  
 |  __add__(self, value, /)
 |      Return self+value.
 |  
 |  __contains__(self, key, /)
 |      Return key in self.
 |  
 |  __eq__(self, value, /)
 |      Return self==value.
 |  
 |  __format__(self, format_spec, /)
 |      Return a formatted version of the string as described by format_spec.
 |  
 |  __ge__(self, value, /)
 |      Return self>=value.
 |  
 |  __getattribute__(self, name, /)
 |      Return getattr(self, name).
 |  
 |  __getitem__(self, key, /)
 |      Return self[key].
 |  
 |  __getnewargs__(...)
 |  
 |  __gt__(self, value, /)
 |      Return self>value.
 |  
 |  __hash__(self, /)
 |      Return hash(self).
 |  
 |  __iter__(self, /)
 |      Implement iter(self).
 |  
 |  __le__(self, value, /)
 |      Return self<=value.
 |  
 |  __len__(self, /)
 |      Return len(self).
 |  
 |  __lt__(self, value, /)
 |      Return self<value.
 |  
 |  __mod__(self, value, /)
 |      Return self%value.
 |  
 |  __mul__(self, value, /)
 |      Return self*value.
 |  
 |  __ne__(self, value, /)
 |      Return self!=value.
 |  
 |  __repr__(self, /)
 |      Return repr(self).
 |  
 |  __rmod__(self, value, /)
 |      Return value%self.
 |  
 |  __rmul__(self, value, /)
 |      Return value*self.
 |  
 |  __sizeof__(self, /)
 |      Return the size of the string in memory, in bytes.
 |  
 |  __str__(self, /)
 |      Return str(self).
 |  
 |  capitalize(self, /)
 |      Return a capitalized version of the string.
 |      
 |      More specifically, make the first character have upper case and the rest lower
 |      case.
 |  
 |  casefold(self, /)
 |      Return a version of the string suitable for caseless comparisons.
 |  
 |  center(self, width, fillchar=' ', /)
 |      Return a centered string of length width.
 |      
 |      Padding is done using the specified fill character (default is a space).
 |  
 |  count(...)
 |      S.count(sub[, start[, end]]) -> int
 |      
 |      Return the number of non-overlapping occurrences of substring sub in
 |      string S[start:end].  Optional arguments start and end are
 |      interpreted as in slice notation.
 |  
 |  encode(self, /, encoding='utf-8', errors='strict')
 |      Encode the string using the codec registered for encoding.
 |      
 |      encoding
 |        The encoding in which to encode the string.
 |      errors
 |        The error handling scheme to use for encoding errors.
 |        The default is 'strict' meaning that encoding errors raise a
 |        UnicodeEncodeError.  Other possible values are 'ignore', 'replace' and
 |        'xmlcharrefreplace' as well as any other name registered with
 |        codecs.register_error that can handle UnicodeEncodeErrors.
 |  
 |  endswith(...)
 |      S.endswith(suffix[, start[, end]]) -> bool
 |      
 |      Return True if S ends with the specified suffix, False otherwise.
 |      With optional start, test S beginning at that position.
 |      With optional end, stop comparing S at that position.
 |      suffix can also be a tuple of strings to try.
 |  
 |  expandtabs(self, /, tabsize=8)
 |      Return a copy where all tab characters are expanded using spaces.
 |      
 |      If tabsize is not given, a tab size of 8 characters is assumed.
 |  
 |  find(...)
 |      S.find(sub[, start[, end]]) -> int
 |      
 |      Return the lowest index in S where substring sub is found,
 |      such that sub is contained within S[start:end].  Optional
 |      arguments start and end are interpreted as in slice notation.
 |      
 |      Return -1 on failure.
 |  
 |  format(...)
 |      S.format(*args, **kwargs) -> str
 |      
 |      Return a formatted version of S, using substitutions from args and kwargs.
 |      The substitutions are identified by braces ('{' and '}').
 |  
 |  format_map(...)
 |      S.format_map(mapping) -> str
 |      
 |      Return a formatted version of S, using substitutions from mapping.
 |      The substitutions are identified by braces ('{' and '}').
 |  
 |  index(...)
 |      S.index(sub[, start[, end]]) -> int
 |      
 |      Return the lowest index in S where substring sub is found,
 |      such that sub is contained within S[start:end].  Optional
 |      arguments start and end are interpreted as in slice notation.
 |      
 |      Raises ValueError when the substring is not found.
 |  
 |  isalnum(self, /)
 |      Return True if the string is an alpha-numeric string, False otherwise.
 |      
 |      A string is alpha-numeric if all characters in the string are alpha-numeric and
 |      there is at least one character in the string.
 |  
 |  isalpha(self, /)
 |      Return True if the string is an alphabetic string, False otherwise.
 |      
 |      A string is alphabetic if all characters in the string are alphabetic and there
 |      is at least one character in the string.
 |  
 |  isascii(self, /)
 |      Return True if all characters in the string are ASCII, False otherwise.
 |      
 |      ASCII characters have code points in the range U+0000-U+007F.
 |      Empty string is ASCII too.
 |  
 |  isdecimal(self, /)
 |      Return True if the string is a decimal string, False otherwise.
 |      
 |      A string is a decimal string if all characters in the string are decimal and
 |      there is at least one character in the string.
 |  
 |  isdigit(self, /)
 |      Return True if the string is a digit string, False otherwise.
 |      
 |      A string is a digit string if all characters in the string are digits and there
 |      is at least one character in the string.
 |  
 |  isidentifier(self, /)
 |      Return True if the string is a valid Python identifier, False otherwise.
 |      
 |      Call keyword.iskeyword(s) to test whether string s is a reserved identifier,
 |      such as "def" or "class".
 |  
 |  islower(self, /)
 |      Return True if the string is a lowercase string, False otherwise.
 |      
 |      A string is lowercase if all cased characters in the string are lowercase and
 |      there is at least one cased character in the string.
 |  
 |  isnumeric(self, /)
 |      Return True if the string is a numeric string, False otherwise.
 |      
 |      A string is numeric if all characters in the string are numeric and there is at
 |      least one character in the string.
 |  
 |  isprintable(self, /)
 |      Return True if the string is printable, False otherwise.
 |      
 |      A string is printable if all of its characters are considered printable in
 |      repr() or if it is empty.
 |  
 |  isspace(self, /)
 |      Return True if the string is a whitespace string, False otherwise.
 |      
 |      A string is whitespace if all characters in the string are whitespace and there
 |      is at least one character in the string.
 |  
 |  istitle(self, /)
 |      Return True if the string is a title-cased string, False otherwise.
 |      
 |      In a title-cased string, upper- and title-case characters may only
 |      follow uncased characters and lowercase characters only cased ones.
 |  
 |  isupper(self, /)
 |      Return True if the string is an uppercase string, False otherwise.
 |      
 |      A string is uppercase if all cased characters in the string are uppercase and
 |      there is at least one cased character in the string.
 |  
 |  join(self, iterable, /)
 |      Concatenate any number of strings.
 |      
 |      The string whose method is called is inserted in between each given string.
 |      The result is returned as a new string.
 |      
 |      Example: '.'.join(['ab', 'pq', 'rs']) -> 'ab.pq.rs'
 |  
 |  ljust(self, width, fillchar=' ', /)
 |      Return a left-justified string of length width.
 |      
 |      Padding is done using the specified fill character (default is a space).
 |  
 |  lower(self, /)
 |      Return a copy of the string converted to lowercase.
 |  
 |  lstrip(self, chars=None, /)
 |      Return a copy of the string with leading whitespace removed.
 |      
 |      If chars is given and not None, remove characters in chars instead.
 |  
 |  partition(self, sep, /)
 |      Partition the string into three parts using the given separator.
 |      
 |      This will search for the separator in the string.  If the separator is found,
 |      returns a 3-tuple containing the part before the separator, the separator
 |      itself, and the part after it.
 |      
 |      If the separator is not found, returns a 3-tuple containing the original string
 |      and two empty strings.
 |  
 |  removeprefix(self, prefix, /)
 |      Return a str with the given prefix string removed if present.
 |      
 |      If the string starts with the prefix string, return string[len(prefix):].
 |      Otherwise, return a copy of the original string.
 |  
 |  removesuffix(self, suffix, /)
 |      Return a str with the given suffix string removed if present.
 |      
 |      If the string ends with the suffix string and that suffix is not empty,
 |      return string[:-len(suffix)]. Otherwise, return a copy of the original
 |      string.
 |  
 |  replace(self, old, new, count=-1, /)
 |      Return a copy with all occurrences of substring old replaced by new.
 |      
 |        count
 |          Maximum number of occurrences to replace.
 |          -1 (the default value) means replace all occurrences.
 |      
 |      If the optional argument count is given, only the first count occurrences are
 |      replaced.
 |  
 |  rfind(...)
 |      S.rfind(sub[, start[, end]]) -> int
 |      
 |      Return the highest index in S where substring sub is found,
 |      such that sub is contained within S[start:end].  Optional
 |      arguments start and end are interpreted as in slice notation.
 |      
 |      Return -1 on failure.
 |  
 |  rindex(...)
 |      S.rindex(sub[, start[, end]]) -> int
 |      
 |      Return the highest index in S where substring sub is found,
 |      such that sub is contained within S[start:end].  Optional
 |      arguments start and end are interpreted as in slice notation.
 |      
 |      Raises ValueError when the substring is not found.
 |  
 |  rjust(self, width, fillchar=' ', /)
 |      Return a right-justified string of length width.
 |      
 |      Padding is done using the specified fill character (default is a space).
 |  
 |  rpartition(self, sep, /)
 |      Partition the string into three parts using the given separator.
 |      
 |      This will search for the separator in the string, starting at the end. If
 |      the separator is found, returns a 3-tuple containing the part before the
 |      separator, the separator itself, and the part after it.
 |      
 |      If the separator is not found, returns a 3-tuple containing two empty strings
 |      and the original string.
 |  
 |  rsplit(self, /, sep=None, maxsplit=-1)
 |      Return a list of the words in the string, using sep as the delimiter string.
 |      
 |        sep
 |          The delimiter according which to split the string.
 |          None (the default value) means split according to any whitespace,
 |          and discard empty strings from the result.
 |        maxsplit
 |          Maximum number of splits to do.
 |          -1 (the default value) means no limit.
 |      
 |      Splits are done starting at the end of the string and working to the front.
 |  
 |  rstrip(self, chars=None, /)
 |      Return a copy of the string with trailing whitespace removed.
 |      
 |      If chars is given and not None, remove characters in chars instead.
 |  
 |  split(self, /, sep=None, maxsplit=-1)
 |      Return a list of the words in the string, using sep as the delimiter string.
 |      
 |      sep
 |        The delimiter according which to split the string.
 |        None (the default value) means split according to any whitespace,
 |        and discard empty strings from the result.
 |      maxsplit
 |        Maximum number of splits to do.
 |        -1 (the default value) means no limit.
 |  
 |  splitlines(self, /, keepends=False)
 |      Return a list of the lines in the string, breaking at line boundaries.
 |      
 |      Line breaks are not included in the resulting list unless keepends is given and
 |      true.
 |  
 |  startswith(...)
 |      S.startswith(prefix[, start[, end]]) -> bool
 |      
 |      Return True if S starts with the specified prefix, False otherwise.
 |      With optional start, test S beginning at that position.
 |      With optional end, stop comparing S at that position.
 |      prefix can also be a tuple of strings to try.
 |  
 |  strip(self, chars=None, /)
 |      Return a copy of the string with leading and trailing whitespace removed.
 |      
 |      If chars is given and not None, remove characters in chars instead.
 |  
 |  swapcase(self, /)
 |      Convert uppercase characters to lowercase and lowercase characters to uppercase.
 |  
 |  title(self, /)
 |      Return a version of the string where each word is titlecased.
 |      
 |      More specifically, words start with uppercased characters and all remaining
 |      cased characters have lower case.
 |  
 |  translate(self, table, /)
 |      Replace each character in the string using the given translation table.
 |      
 |        table
 |          Translation table, which must be a mapping of Unicode ordinals to
 |          Unicode ordinals, strings, or None.
 |      
 |      The table must implement lookup/indexing via __getitem__, for instance a
 |      dictionary or list.  If this operation raises LookupError, the character is
 |      left untouched.  Characters mapped to None are deleted.
 |  
 |  upper(self, /)
 |      Return a copy of the string converted to uppercase.
 |  
 |  zfill(self, width, /)
 |      Pad a numeric string with zeros on the left, to fill a field of the given width.
 |      
 |      The string is never truncated.
 |  
 |  ----------------------------------------------------------------------
 |  Static methods defined here:
 |  
 |  __new__(*args, **kwargs) from builtins.type
 |      Create and return a new object.  See help(type) for accurate signature.
 |  
 |  maketrans(...)
 |      Return a translation table usable for str.translate().
 |      
 |      If there is only one argument, it must be a dictionary mapping Unicode
 |      ordinals (integers) or characters to Unicode ordinals, strings or None.
 |      Character keys will be then converted to ordinals.
 |      If there are two arguments, they must be strings of equal length, and
 |      in the resulting dictionary, each character in x will be mapped to the
 |      character at the same position in y. If there is a third argument, it
 |      must be a string, whose characters will be mapped to None in the result.

capitalize(): It is used to return a string after converting first character of a string to capital letter, if the first character is a lowercase letter.

>>> string1="gargs academy"
>>> string1
'gargs academy'

>>> string1.capitalize()
'Gargs academy'

>>>#'G' will remain as it is
>>> string1="Gargs academy"
>>> string1.capitalize()
'Gargs academy'

>>>#'1' will remain as it is
>>> string1="1gargs academy"
>>> string1.capitalize()
'1gargs academy'

>>>#'+' will remain as it is
>>> string1="+gargs academy"
>>> string1.capitalize()
'+gargs academy'

We can also store the result in another string variable as:

>>> string1="gargs academy"
>>> string1
'gargs academy'

>>> string2=string1.capitalize()
>>> string2
'Gargs academy'

But the original string remains unchanged.

>>> string1="gargs academy"
>>> string1
'gargs academy'

>>> string2=string1.capitalize()
>>> string2
'Gargs academy'

>>> string1
'gargs academy'

title(): It is used to return a string with title case ie first alphabet character of each word capitalized.

>>> string1="gargs academy"
>>> string1.title()
'Gargs Academy'

>>> string1="1gargs 2academy"
>>> string1.title()
'1Gargs 2Academy'

>>> string1="1+2gargs 3#4academy"
>>> string1.title()
'1+2Gargs 3#4Academy'

We can also store the result in another string variable as:

>>> string1="gargs academy"
>>> string1
'gargs academy'

>>> string2=string1.title()
>>> string2
'Gargs Academy'

But the original string remains unchanged.

>>> string1="gargs academy"
>>> string1
'gargs academy'

>>> string2=string1.title()
>>> string2
'Gargs Academy'

>>> string1
'gargs academy'

lower(): It is used to return a string after converting the string to lowercase letters.

>>> string1="Gargs Academy"
>>> string1
'Gargs Academy'

>>> string1.lower()
'gargs academy'

We can also store the result in another string variable as:

>>> string1="Gargs Academy"
>>> string1
'Gargs Academy'


>>> string2=string1.lower()
>>> string2
'gargs academy'

But the original string remains unchanged.

>>> string1="Gargs Academy"
>>> string1
'Gargs Academy'

>>> string2=string1.lower()
>>> string2
'gargs academy'

>>> string1
'Gargs Academy'

upper(): It is used to return a string after converting the string to uppercase letters.

>>> string1="Gargs Academy"
>>> string1
'Gargs Academy'

>>> string1.upper()
'GARGS ACADEMY'

We can also store the result in another string variable as:

>>> string1="Gargs Academy"
>>> string1
'Gargs Academy'

>>> string2=string1.upper()
>>> string2
'GARGS ACADEMY'

But the original string remains unchanged.

>>> string1="Gargs Academy"
>>> string1
'Gargs Academy'

>>> string2=string1.upper()
>>> string2
'GARGS ACADEMY'

>>> string1
'Gargs Academy'

count(): To count the frequency of a string in the given string.

>>> string1="gargs academy"
>>> string1
'gargs academy'

>>> string1.count("a")
3

If the string does not exist in the given string, it returns 0

>>> string1="gargs academy"
>>> string1
'gargs academy'

>>> string1.count("t")
0

find(): It is used to find the index position of first occurrence of a string in the given string.

>>> string1="Gargs Academy"
>>> string1
'Gargs Academy'

>>> string1.find("a")
1

If the string is not present in the given string, it will return -1

>>> string1="Gargs Academy"
>>> string1
'Gargs Academy'

>>> string1.find("t")
-1

We can also find the string in any sub part of the given string as
stringname.find(substring,start,stop)
default value of start is 0
default value of stop is len(string)
substring must be specified as an argument in the find(), otherwise python will give error.

>>> string1="Gargs Academy"
>>> string1
'Gargs Academy'

>>>#finds the position of "a" in the given string starting from 2nd character
>>> string1.find("a",2)
8

>>>#finds the position of "a" in the given string starting from 2nd character and upto 4th character
>>> string1.find("a",2,4)
-1

>>> string1.find()
Traceback (most recent call last):
  File "<pyshell#14>", line 1, in <module>
    string1.find()
TypeError: find() takes at least 1 argument (0 given)

index(): It is used to find the index position of first occurrence of a string in the given string.

>>> string1="gargs academy"
>>> string1
'gargs academy'

>>> string1.index("a")
1

If the string is not present in the given string, it will result into an error as:

>>> string1="gargs academy"
>>> string1
'gargs academy'

>>> string1.index("t")
Traceback (most recent call last):
  File "<pyshell#67>", line 1, in <module>
    string1.index("t")
ValueError: substring not found

We can also find the string in any sub part of the given string as
stringname.index(substring,start,stop)
default value of start is 0
default value of stop is len(string)
substring must be specified as an argument in the index(), otherwise python will give error.

>>> string1="Gargs Academy"
>>> string1
'Gargs Academy'

>>>#finds the position of "a" in the given string starting from 2nd character
>>> string1.index("a",2)
8

>>>#finds the position of "a" in the given string starting from 2nd character and upto 4th character
>>> string1.index("a",2,4)
-1

>>> string1.index()
Traceback (most recent call last):
  File "<pyshell#31>", line 1, in <module>
    string1.index()
TypeError: index() takes at least 1 argument (0 given)

endswith(): It returns True, if the given string ends with the string specified as an argument, considering the case sensitivity

>>> string1="gargs academy"

>>> string1.endswith("my")
True

>>> string1.endswith("My")
False

>>> string1.endswith("ay")
False

startswith(): It returns True, if the given string starts with the string specified as an argument, considering the case sensitivity

>>> string1="gargs academy"

>>> string1.startswith("gargs")
True

>>> string1.startswith("Gargs")
False

>>> string1.startswith("Sheetal")
False

isalnum(): It returns True if all the characters of the given string are alphanumeric ie alphabets or digits only

>>>#Returns False as it contains blank space which is not alphanumeric
>>> string1="Gargs Academy 9467863365"
>>> string1.isalnum()
False

>>> string1="GargsAcademy9467863365"
>>> string1.isalnum()
True

isalpha(): It returns True if all the characters of the given string are alphabets only.

>>>#Returns False as it also contains blank space
>>> string1="Gargs Academy 9467863365"
>>> string1.isalpha()
False

>>>#Returns False as it also contains digits 
>>> string2="GargsAcademy9467863365"
>>> string2.isalpha()
False

>>>#Returns True as it contains only alphabets
>>> string3="GargsAcademy"
>>> string3.isalpha()
True

isdigit(): It returns True if all the characters of the given string are digits only.

>>>#Returns False as it also contains alphabets and blank space
>>> string1="Gargs Academy 9467863365"
>>> string1.isdigit()
False

>>>#Returns False as it also contains alphabets
>>> string2="GargsAcademy9467863365"
>>> string2.isdigit()
False

>>>#Returns True as it contains only digits
>>> string3="9467863365"
>>> string3.isdigit()
True

islower(): It returns True if all the characters of the given string are lowercase letters only. It returns False even if any one character is in uppercase.

>>>#Returns False as it also contains uppercase alphabets
>>> string1="Gargs Academy 9467863365"
>>> string1.islower()
False

>>>#Returns True as it contains only lowercase letters/digits/symbols
>>> string2="gargs academy 9467863365"
>>> string2.islower()
True

>>>#Returns False as it also contains uppercase alphabets
>>> string3="Gargs Academy"
>>> string3.islower()
False

>>>#Returns True as it contains only lowercase letters
>>> string4="gargs academy"
>>> string4.islower()
True

isupper(): It returns True if all the characters of the given string are uppercase letters only. It returns False even if any one character is in lowercase.

>>>#Returns False as it also contains lowercase alphabets
>>> string1="Gargs Academy 9467863365"
>>> string1.isupper()
False

>>>#Returns True as it contains only uppercase letters/digits/symbols
>>> string2="GARGS ACADEMY 9467863365"
>>> string2.isupper()
True

>>>#Returns False as it also contains lowercase alphabets
>>> string3="Gargs Academy"
>>> string3.isupper()
False

>>>#Returns True as it contains only uppercase letters
>>> string4="GARGS ACADEMY"
>>> string4.isupper()
True

isspace(): It returns True if all the characters of the given string are blank spaces only. It returns False even if any one character is not blank space.

#Returns False as string also contains alphabets and digits
>>> string1="Gargs Academy 9467863365"
>>> string1.isspace()
False

#Returns False as string also contains alphabets
>>> string2="Gargs Academy"
>>> string2.isspace()
False

#Returns False as string also contains digits
>>> string3="9467863365 9467282393"
>>> string3.isspace()
False

#Returns False as string is empty
>>> string4=""
>>> string4.isspace()
False

#Returns True as string contains only space
>>> string5=" "
>>> string5.isspace()
True

#Returns True as string contains only space. Note that \t and \n are also spaces
>>> string6=" \t\n"
>>> string6.isspace()
True

lstrip(): It returns a string after removing all the occurrences of all the possible subsets/combinations of the specified string from the left side of the given string.

>>>#It will remove all the occurrences of all the subsets of "XP" ie "X" , "P" and "XP" from left side
>>> string1="XPXPX Gargs Academy"
>>> string1.lstrip("XP")
' Gargs Academy'

>>>#It will remove all the occurrences of all the subsets of "X" ie "X", "XX" from left side
>>> string2="XXXPXPX Gargs Academy"
>>> string2.lstrip("X")
'PXPX Gargs Academy'

>>>#It will not remove anything because P is not present on left hand side of the given string
>>> string3="XPXPX Gargs Academy"
>>> string3.lstrip("P")
'XPXPX Gargs Academy'

>>>#It will remove all the occurrences of all the subsets of "X" ie "X" , "XX" etc from left side
>>> string4="XXXX Gargs Academy"
>>> string4.lstrip("X")
' Gargs Academy'

We can also store the result in a string variable as

>>> string1="XXXX Gargs Academy"

>>> string2=string1.lstrip("X")
>>> string2
' Gargs Academy'

But the original string remains unchanged as

>>> string1="XXXX Gargs Academy"

>>> string2=string1.lstrip("X")
>>> string2
' Gargs Academy'

>>> string1
'XXXX Gargs Academy'

If we don’t specify any string, then blank spaces are removed from left side of the string as

>>> string1="   Gargs Academy"

>>> string1.lstrip()
'Gargs Academy'

rstrip(): It returns a string after removing all the occurrences of all the possible subsets/combinations of the specified string from the right side of the given string.

>>>#It will remove all the occurrences of all the subsets of "XP" ie "X" , "P" and "XP" from right side
>>> string1="Gargs Academy XPXPX"
>>> string1.rstrip("XP")
'Gargs Academy '

>>>#It will remove all the occurrences of all the subsets of "X" ie "X", "XX" from right side
>>> string2="Gargs Academy XPXPX"
>>> string2.rstrip("X")
'Gargs Academy XPXP'

>>>#It will not remove anything because P is not present on right hand side of the given string
>>> string3="Gargs Academy XPXPX"
>>> string3.rstrip("P")
'Gargs Academy XPXPX'

>>>#It will remove all the occurrences of all the subsets of "X" ie "X" , "XX" etc from right side
>>> string4="Gargs Academy XXXX"
>>> string4.rstrip("X")
'Gargs Academy '

We can also store the result in a string variable as

>>> string1="Gargs Academy XXXX"

>>> string2=string1.rstrip("X")
>>> string2
'Gargs Academy '

But the original string remains unchanged as

>>> string1="Gargs Academy XXXX"

>>> string2=string1.rstrip("X")
>>> string2
'Gargs Academy '

>>> string1
'Gargs Academy XXXX'

If we don’t specify any string, then blank spaces are removed from right side of the string as

>>> string1="Gargs Academy   "

>>> string1.rstrip()
'Gargs Academy'

strip(): It returns a string after removing all the occurrences of all the possible subsets/combinations of the specified string from both sides of the given string.

>>>#It will remove all the occurrences of all the subsets of "XP" ie "X" , "P" and "XP" from both sides
>>> string1="XPXPX Gargs Academy XPXPX"
>>> string1.strip("XP")
' Gargs Academy '

>>>#It will remove all the occurrences of all the subsets of "X" ie "X", "XX" from both sides
>>> string2="XPXPX Gargs Academy XPXPX"
>>> string2.strip("X")
'PXPX Gargs Academy XPXP'

>>>#It will not remove anything because P is not present on left and right hand side of the given string
>>> string3="XPXPX Gargs Academy XPXPX"
>>> string3.strip("P")
'XPXPX Gargs Academy XPXPX'

>>>#It will not remove anything from left because P is not present on left hand side of the given string
>>> string4="XPXPX Gargs Academy XPXP"
>>> string4.strip("P")
'XPXPX Gargs Academy XPX'

>>>#It will not remove anything from right because P is not present on right hand side of the given string
>>> string5="PXPX Gargs Academy XPXPX"
>>> string5.strip("P")
'XPX Gargs Academy XPXPX'

>>>#It will remove all the occurrences of all the subsets of "X" ie "X" , "XX" etc from both sides
>>> string6="XXXX gargs academy XXXXXX"
>>> string6.strip("X")
' gargs academy '

We can also store the result in a string variable as

>>> string1="XXXX Gargs Academy XXXX"

>>> string2=string1.strip("X")
>>> string2
' Gargs Academy '

But the original string remains unchanged as

>>> string1="XXXX Gargs Academy XXXX"

>>> string2=string1.strip("X")
>>> string2
' Gargs Academy '

>>> string1
'XXXX Gargs Academy XXXX'

If we don’t specify any string, then blank spaces are removed from both sides of the string as

>>> string1="  Gargs Academy   "

>>> string1.strip()
'Gargs Academy'

replace(): It is used to replace n number of occurrences of a string with a new string.

>>> string1="garg garg garg academy"
>>> string1.replace("garg","GARG",2)
'GARG GARG garg academy'

>>> string1="garg garg garg academy"
>>> string1.replace("garg","GARG",0)
'garg garg garg academy'

Default value of n is all occurrences.

>>> string1="garg garg garg academy"
>>> string1.replace("garg","GARG")
'GARG GARG GARG academy'

We can also store the result in a string variable as

>>> string1="garg garg garg academy"

>>> string2=string1.replace("garg","GARG")
>>> string2
'GARG GARG GARG academy'

But the original string remains unchanged as

>>> string1="garg garg garg academy"

>>> string2=string1.replace("garg","GARG")
>>> string2
'GARG GARG GARG academy'

>>> string1
'garg garg garg academy'

It will return the given string as it is, if the specified old string is not found in the main string.

>>> string1="garg garg garg academy"
>>> string1.replace("gupta","GUPTA")
'garg garg garg academy'

join(): It takes all items in an iterable of strings and joins them into one string, by inserting the specified string in between every string of an iterable of strings.

>>> string1="#@"

>>> string2="garg"
>>> string1.join(string2)
'g#@a#@r#@g'

>>> list1=["gargs","academy"]
>>> string1.join(list1)
'gargs#@academy'

>>> tuple1=("gargs","academy")
>>> string1.join(tuple1)
'gargs#@academy'

>>>#since sets are unordered collection of values, so result may come in different order
>>> set1={"gargs","academy"}
>>> string1.join(set1)
'academy#@gargs'

>>>#It will join taking the keys of dictionary as the strings of iterables
>>> dictionary1={"gargs":1,"academy":2}
>>> string1.join(dictionary1)
'gargs#@academy'

We can also store the result in another string variable as:

>>> string1="#@"
>>> string2="garg"

>>> string3=string1.join(string2)
>>> string3
'g#@a#@r#@g'

But the original strings remains unchanged

>>> string1="#@"
>>> string2="garg"

>>> string3=string1.join(string2)
>>> string3
'g#@a#@r#@g'

>>> string1
'#@'
>>> string2
'garg'

If the iterable does not contains strings, then python will give error as:

>>> string1="#@"

>>> list1=["gargs academy",9467863365]
>>> string1.join(list1)
Traceback (most recent call last):
  File "<pyshell#26>", line 1, in <module>
    string1.join(list1)
TypeError: sequence item 1: expected str instance, int found

>>> tuple1=("gargs academy",9467863365)
>>> string1.join(tuple1)
Traceback (most recent call last):
  File "<pyshell#27>", line 1, in <module>
    string1.join(tuple1)
TypeError: sequence item 1: expected str instance, int found

>>> set1={"gargs academy",9467863365}
>>> string1.join(set1)
Traceback (most recent call last):
  File "<pyshell#28>", line 1, in <module>
    string1.join(set1)
TypeError: sequence item 1: expected str instance, int found

>>> dictionary1={"gargs academy":1,9467863365:2}
>>> string1.join(dictionary1)
Traceback (most recent call last):
  File "<pyshell#29>", line 1, in <module>
    string1.join(dictionary1)
TypeError: sequence item 1: expected str instance, int found

partition(): It searches for a specified string, and splits the string into a tuple containing three elements.
1) The first element contains the part before the specified string.
2) The second element contains the specified string.
3) The third element contains the part after the string.

>>> string1="garg academy 9467863365"

>>> string1.partition("academy")
('garg ', 'academy', ' 9467863365')

>>> string1=""
>>> string1.partition(" ")
('', '', '')

We can also store the result in a tuple as

>>> string1="garg academy 9467863365"

>>> string2=string1.partition("academy")
>>> string2
('garg ', 'academy', ' 9467863365')

But the original string remains unchanged

>>> string1="garg academy 9467863365"

>>> string2=string1.partition("academy")
>>> string2
('garg ', 'academy', ' 9467863365')
>>> string1
'garg academy 9467863365'

If the specified string does not exist in the given string, then second and third part of the tuple is an empty string as

>>> string1="garg academy 9467863365"

>>> string1.partition("center")
('garg academy 9467863365', '', '')

If the specified string appears multiple times in the given string, then it will partition the given string at only first occurrence of specified string.

>>> string1="garg academy 9467863365 math academy and computer academy"
>>> string1.partition("academy")
('garg ', 'academy', ' 9467863365 math academy and computer academy')

>>> string1="garg academy 9467863365"
>>> string1.partition(" ")
('garg', ' ', 'academy 9467863365')

If we don’t specify the string for partitioning, then python will give error as

>>> string1="garg academy 9467863365"

>>> string1.partition("")
Traceback (most recent call last):
  File "<pyshell#6>", line 1, in <module>
    string1.partition("")
ValueError: empty separator

split(): It will split a string into a list.
stringname.split(separator, maxsplit)
Separator specifies the separator to use when splitting the string. By default any whitespace is a separator.
maxspli specifies how many splits to do. Default value is -1, which is “all occurrences”

>>> string1="garg academy 9467863365 math academy and computer academy"
>>> string1.split()
['garg', 'academy', '9467863365', 'math', 'academy', 'and', 'computer', 'academy']

>>> string1="garg academy 9467863365 math academy and computer academy"
>>> string1.split(" ",2)
['garg', 'academy', '9467863365 math academy and computer academy']

We can also store the result in a list variable as

>>> string1="garg academy 9467863365 math academy and computer academy"

>>> list1=string1.split()
>>> list1
['garg', 'academy', '9467863365', 'math', 'academy', 'and', 'computer', 'academy']

But the original string remains unchanged

>>> string1="garg academy 9467863365 math academy and computer academy"

>>> list1=string1.split()
>>> list1
['garg', 'academy', '9467863365', 'math', 'academy', 'and', 'computer', 'academy']

>>> string1
'garg academy 9467863365 math academy and computer academy'
error: You can only copy the programs code and output from this website. You are not allowed to copy anything else.