Built-In String Functions in Python
Built-In String Functions in Python
The following table lists all the functions that can be used with the string type
in Python 3.
Method Description
1.capitalize() Returns the copy of the string with its first character
capitalized and the rest of the letters are in lowercased.
Output
Original String: hello world!
New String: Hello world!
===================================
2.casefold() Returns a lowered case string. It is similar to the lower()
method, but the casefold() method
converts more characters into lower case.
example:
print('HELLO WORLD'.casefold())
========================
3.center() Returns a new centered string of the specified length, which is padded
with the specified character. The deafult character is space.
Syntax:
str.center(width, fillchar)
Parameters:
width : The total length of the string.
fillchar :(Optional) A character to be used for padding.
Return Value:
Returns a string.
Example:
greet='Hi'
print(greet.center(4, '-'))
print(greet.center(5, '*'))
print(greet.center(6, '>'))
Output
'-Hi-'
'**Hi*'
'>>Hi>>'
======================
Syntax:
str.count(substring, start, end)
Parameters:
substring: A string whose count has to be found.
start: (Optional) The starting index of the string from where the search has to
begin . Default is 0.
end: (Optional) The ending index of the string where the search has to end. Default
is the end of the string.
Return Value:
An integer value indicating the number of times a substring presents in a given
string.
The following example counts the number of occurrences of the given substring:
total = mystr.count('Tutorials')
print('Number of occurrences of "Tutorials":', total)
total = mystr.count('tutorials')
print('Number of occurrences of "tutorials":', total)
Output
Number of occurrences of "Tutorials": 1
Number of occurrences of "tutorials": 0
example2:
>>>python strcountdemo.py
Number of occurrences between 0 to 15 index: 1
Number of occurrences between 15 to 25 index: 0
Number of occurrences from 25th index till end: 1
=======================================
5.endswith() Returns True if a string ends with the specified suffix (case-
sensitive), otherwise returns False.
Synatx:
str.endswith(suffix, start, end)
Parameters:
suffix : (Required) String or tuple of strings to look for.
start : (Optional) Starting index at which search should start. Defaults to
0.
end : (Optional) Ending index at which the search should end. Defaults to the
last index of a string.
Return Value:
Returns True if the string ends with the specified suffix, otherwise returns False.
Example:
Output
True
True
True
True
False
=================================
6.expandtabs() Returns a string with all tab characters \t replaced with one or
more space, depending on the number of characters before \t and the
specified tab size.
syntax:
str.expandtabs(tabsize)
Parameters:
tabsize: size of whitespaces characters to replace \t. Default is 8.
Return Value:
Returns a string where all '\t' characters are replaced with whitespace characters
until the next multiple of tab size parameter.
example:
>>> '1234\t'.expandtabs()
'1234 '
>>> '1234\t1234'.expandtabs()
'1234 1234'
>>> '1234\t1234\t'.expandtabs()
'1234 1234 '
===========================================
7.find() Returns the index of the first occurence of a substring in the given
string (case-sensitive). If the substring is not found it returns -1.
Syntax:
str.find(substr, start, end)
Parameters:
substr: (Required) The substring whose index has to be found.
start: (Optional) The starting index position from where the searching should
start in the string. Default is 0.
end: (Optional) The ending index position untill the searching should happen.
Default is end of the string.
Example: find()
greet='Hello World!'
print("Index of 'H': ", greet.find('H'))
print("Index of 'h': ", greet.find('h'))
print("Index of 'e': ", greet.find('e'))
print("Index of 'World': ", greet.find('World'))
Output
Index of 'H': 0
Index of 'h': -1
Index of 'e': 1
Index of 'World': 6
==================================
8.index() Returns the index of the first occurence of a substring in the given
string.
Syntax:
str.index(substr, start, end)
Parameters:
substr: (Required) The substring whose index has to be found.
start: (Optional) The starting index position from where the searching should
start in the string. Default is 0.
end: (Optional) The ending index position untill the searching should happen.
Default is end of the string.
Return Value:
An integer value indicating an index of the specified substring.
Example:
>>>greet='Hello World!'
print('Index of H: ', greet.index('H'))
print('Index of e: ', greet.index('e'))
print('Index of l: ', greet.index('l'))
print('Index of World: ', greet.index('World'))
Output
Index of H: 0
Index of e: 1
Index of l: 2
Index of World: 6
=====================================
9.isalnum() Returns True if all characters in the string are alphanumeric (either
alphabets or numbers). If not, it returns False.
Syntax:
str.isalnum()
example1:
mystr = 'Hello123'
print(mystr.isalnum())
mystr = '12345'
print(mystr.isalnum())
mystr = 'PythonTutorials'
print(mystr.isalnum())
Output
True
True
True
=========================================
Syntax: isalpha()
example:
mystr = 'HelloWorld'
print(mystr.isalpha()) # returns True
mystr = 'Hello World'
print(mystr.isalpha()) # returns False
Output
True
False
False
Flase
===============================
Syntax:
str.isascii()
Parameters:
None.
Return Value:
Example: isascii()
mystr = 'ABC'
print(mystr.isascii())
mystr = '012345'
print(mystr.isascii())
mystr = 'ABC'
print(mystr.isascii())
Output
True
True
True
=====================================================
12.isdecimal() Returns True if all characters in a string are decimal
characters. If not, it returns False.
Example: isdecimal()
numstr = '12345'
print(numstr.isdecimal())
numstr = '10.50'
print(numstr.isdecimal())
alnumstr = '123A'
print(alnumstr.isdecimal())
mystr = 'Python'
print(mystr.isdecimal())
Output
True
False
False
False
===================================
13.isdigit() Returns True if all characters in a string are digits or
Unicode char of a digit. If not, it returns False.
Example: str.isdigit()
mystr = '12345'
print(mystr.isdigit())
mystr = '10.5'
print(mystr.isdigit())
mystr = 'python'
print(mystr.isdigit())
Output
True
False
False
==============================
Example: isidentifier()
>>> lang='Python'
>>> lang.isidentifier()
True
==============================================
The following eample checks whether the given string is in lowercase or not.
Example:
>>> mystr = 'hello world'
>>> mystr.islower()
True
>>> mystr = 'Hello world'
>>> mystr.islower()
False
>>> mystr = 'python is #1'
>>> mystr.islower()
True
===============================================
16.isnumeric() Checks whether all the characters of the string are numeric
characters or not. It will return True if all characters are numeric and will
return False even if one character is non-numeric.
Example: isnumeric()
>>> numstr = '100' #numeric digits
>>> numstr.isnumeric()
True
============================
17.isprintable() Returns True if all the characters of the given string are
Printable. It returns False even if one character is Non-Printable.
18.isspace() Returns True if all the characters of the given string are
whitespaces. It returns False even if one character is not whitespace.
19.istitle() Checks whether each word's first character is upper case and the
rest are in lower case or not. It returns True if a string is titlecased;
otherwise, it returns False. The symbols and numbers are ignored.
19.isupper() Returns True if all characters are uppercase and False even if
one character is not in uppercase.
20.join() Returns a string, which is the concatenation of the string (on which it
is called) with the string elements of the specified iterable as an argument.
21.ljust() Returns the left justified string with the specified width. If the
specified width is more than the string length, then the string's remaining part is
filled with the specified fillchar.
22.lower() Returns the copy of the original string wherein all the characters are
converted to lowercase.
24.maketrans() Returns a mapping table that maps each character in the given
string to the character in the second string at the same position. This mapping
table is used with the translate() method, which will replace characters as per the
mapping table.
25.partition() Splits the string at the first occurrence of the specified string
separator sep argument and returns a tuple containing three elements, the part
before the separator, the separator itself, and the part after the separator.
27.rfind() Returns the highest index of the specified substring (the last
occurrence of the substring) in the given string.
28.rindex() Returns the index of the last occurence of a substring in the given
string.
29.rjust() Returns the right justified string with the specified width. If the
specified width is more than the string length, then the string's remaining part is
filled with the specified fill char.
30.rpartition() Splits the string at the last occurrence of the specified string
separator sep argument and returns a tuple containing three elements, the part
before the separator, the separator itself, and the part after the separator.
31.rsplit() Splits a string from the specified separator and returns a list object
with string elements.
33.split() Splits the string from the specified separator and returns a list
object with string elements.
34.splitlines() Splits the string at line boundaries and returns a list of lines
in the string.
36.strip() Returns a copy of the string by removing both the leading and the
trailing characters.
38.title() Returns a string where each word starts with an uppercase character,
and the remaining characters are lowercase.
40.upper() Returns a string in the upper case. Symbols and numbers remain
unaffected.
41.zfill() Returns a copy of the string with '0' characters padded to the left. It
adds zeros (0) at the beginning of the string until the length of a string equals
the specified width parameter.
===================================================
String Methods:
The capitalize() method returns the copy of the string with its first character
capitalized and the rest of the letters lowercased.
Syntax:
string.capitalize()
Parameters:
No parameters.
Return Value:
Returns a capitalized string.
Output
Original String: hello world!
New String: Hello world!
Notice that the method does not change the original string on which it is being
called. It returns a new string.
In the above example, only the first letter of the sentence is capitalized because
the method only capitalizes the first letter of the string. The rest of the letters
are lowercased even if they are capital in the original string.
===============================
python code:
python code:
python code:
python code:
python code:
python code: