0% found this document useful (0 votes)
22 views

Built-In String Functions in Python

Copyright
© © All Rights Reserved
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
22 views

Built-In String Functions in Python

Copyright
© © All Rights Reserved
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 11

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.

Example1: Capitalize a word Copy


a = 'hello world!'
b = a.capitalize()
print('Original String:', a)
print('New String:', b)

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:

mystr = 'CVR College'


print(mystr.casefold())

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>>'
======================

4.count() Searches (case-sensitive) the specified substring in the given string


and returns an integer indicating occurrences of the substring.

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:

Example1: Counting Case-sensitive Substring

mystr = 'Python.org is a free online Tutorials website'

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:

mystr = 'TutorialsPython is a free online Tutorials website'


substr = 'Tutorials'

total = mystr.count(substr, 0, 15) # start 0, end 15


print('Number of occurrences between 0 to 15 index:',total)

total = mystr.count(substr, 15, 25) # start 15, end 25


print('Number of occurrences between 15 to 25 index:',total)

total = mystr.count(substr, 25) # start 25


print('Number of occurrences from 25th index till end:',total)

>>>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:

mystr = 'Python is a programming language.'

print(mystr.endswith('.')) # returns True


print(mystr.endswith('age.')) # returns True
print(mystr.endswith('language.')) # returns True
print(mystr.endswith(' programming language.')) # returns True
print(mystr.endswith('age')) # returns False, . is missing

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

=========================================

10.isalpha() Returns True if all characters in a string are alphabetic (both


lowercase and uppercase) and returns False if at least one character is not an
alphabet.

Syntax: isalpha()

example:

mystr = 'HelloWorld'
print(mystr.isalpha()) # returns True
mystr = 'Hello World'
print(mystr.isalpha()) # returns False

print('12345'.isalpha()) # returns False


print('#Hundred'.isalpha()) # returns False

Output
True
False
False
Flase

===============================

11.isascii() Returns True if the string is empty or all characters in the


string are ASCII.

ASCII stands for American Standard Code for Information Interchange.


It is a character endcoding standard that uses numbers from 0 to 127 to represent
English characters.
For example, ASCII code for the character A is 65, and 90 is for Z.
Similarly, ASCII code 97 is for a and 122 is for z.
ASCII codes also used to represent characters such as tab, form feed, carriage
return, and also some symbols.

Syntax:
str.isascii()
Parameters:
None.

Return Value:

Returns True if a string is ASCII, else returns False.

The following example demonstrates the isascii() method.

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

==============================

14.isidentifier() Checks whether a string is valid identifier string or not. It


returns True if the string is a valid identifier otherwise returns False.

Example: isidentifier()

>>> lang='Python'
>>> lang.isidentifier()
True

>>> greet='Hello World'


>>> greet.isidentifier() # includes space so returns False
False

==============================================

15.islower() Checks whether all the characters of a given string are


lowercased or not. It returns True if all characters are lowercased and False even
if one character is uppercase.

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.

23.lstrip() Returns a copy of the string by removing leading characters specified


as an argument.

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.

26.replace() Returns a copy of the string where all occurrences of a substring


are replaced with another substring.

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.

32.rstrip() Returns a copy of the string by removing the trailing characters


specified as argument.

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.

35.startswith() Returns True if a string starts with the specified prefix. If


not, it returns False.

36.strip() Returns a copy of the string by removing both the leading and the
trailing characters.

37.swapcase() Returns a copy of the string with uppercase characters converted


to lowercase and vice versa. Symbols and letters are ignored.

38.title() Returns a string where each word starts with an uppercase character,
and the remaining characters are lowercase.

39.translate() Returns a string where each character is mapped to its


corresponding character in the translation table.

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:

Python capitalize() Method

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.

The following example converts the first letter of a word to capital.

Example1: Capitalize a word Copy


a = 'hello world!'
b = a.capitalize()
print('Original String:', a)
print('New String:', b)

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.

The following example capitalizes a sentence.


Example2: Capitalizing a Sentence Copy
a = 'mumBai Is AWesome'
b = a.capitalize()
print('Original String:', a)
print('New String:', b)
Output
Original String: mumBai Is AWesome
New String: Mumbai is awesome

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.

===============================

examples of built-in string methods in Python:

1.upper(): Converts all characters in a string to uppercase.

python code:

string = "hello world"


upper_string = string.upper()
print(upper_string) # Output: HELLO WORLD

2.lower(): Converts all characters in a string to lowercase.

python code:

string = "Hello World"


lower_string = string.lower()
print(lower_string) # Output: hello world

3.capitalize(): Capitalizes the first character of a string.


python code:

string = "hello world"


capitalized_string = string.capitalize()
print(capitalized_string) # Output: Hello world

4.title(): Capitalizes the first character of each word in a string.

python code:

string = "hello world"


title_string = string.title()
print(title_string) # Output: Hello World

5.strip(): Removes leading and trailing whitespaces from a string.

python code:

string = " hello world "


stripped_string = string.strip()
print(stripped_string) # Output: hello world

6.replace(): Replaces occurrences of a substring with another substring.


python code:
string = "hello world"
new_string = string.replace("world", "universe")
print(new_string) # Output: hello universe

7.split(): Splits a string into a list of substrings based on a delimiter.

python code:

string = "hello world"


split_string = string.split()
print(split_string) # Output: ['hello', 'world']

8.join(): Concatenates elements of an iterable with a specified separator.

python code:

words = ['hello', 'world']


joined_string = ' '.join(words)
print(joined_string) # Output: hello world

You might also like