Python String Methods

Contents show

Python String Methods

Python String Methods
fig: Python String Methods

The Python also offers many built-in functions and methods for string manipulation. The string manipulation methods that are being discussed below can be applied to strings as per following syntax :

<stringobject>.<method name> ( )

For instance, if you have a string namely str = “Rock the World” and you want to find its length you will write the code somewhat like shown below :

>>> str = "Rock the World."
>>> str.length( ) <---see the string object is str and method name    
15                     is length( ).
>>> str2 = "New World"
>>> str2.length( )
9

Python’s built-in string manipulation methods

1. Python String capitalize()

string.capitalize( )


returns a copy of the string with its first character capitalized.


string.capitalize( ) Example :

>>> 'i love my India'.capitalize( )
I love my India

2. string.find(sub, start, end)


Returns the lowest index in the string where the sub string sub is found within the slice range of start and end. Returns -1 if sub is not found.

string.find(sub, start, end) Example :

>>> string = 'it goes as - ringa ringa roses'
>>> sub = 'ringa'
>>> string.find(sub, 15, 22)
-1
>>> string.find(sub, 15, 25)
19

3. Python String isalnum()

string.isalnum( )


Returns True if the characters in the string are alphanumeric (alphabets or numbers) and there is at least one character, False otherwise.


string.isalnum( ) Example :

>>> string = "abc123"
>>> string2 = "hello"
>>> string3 = "12345"
>>> string4 = ' '

>>> string.isalnum( )
True
>>> string2.isalnum( )
True
>>> string3.isalnum( )
True
>>> string4.isalnum( )
False

4. Python String isalpha()

string.isalpha( )


Returns True if all characters in the string are alphabetic and there is at least one character, False otherwise.


string.isalpha( ) Example :

>>> string = "abc123"
>>> string2 = "hello"
>>> string3 = "12345"
>>> string4 = ' '

>>> string.isalpha( )
False
>>> string2.isalpha( )
True
>>> string3.isalpha( )
False
>>> string4.isalpha( )
False

5. Python String isdigit()

string.isdigit( )


Returns True if all the character in the string are digits. There must be at least one digit, otherwise if returns False.

string.isdigit( ) Example :

>>> string = "abc123"
>>> string2 = "hello"
>>> string3 = "12345"
>>> string4 = ' '

>>> string.isdigit( )
False
>>> string2.isdigit( )
False
>>> string3.isdigit( )
False
>>> string4.isdigit( )
True

6. Python String isspace()

string.isspace( )


Returns True if there are only whitespace characters in the string. There must be at least one character. It returns False otherwise.


string.isspace( ) Example :

>>> string = "   "     # stores three spaces
>>> string2 = " "     # an empty string
>>> string.isspace( )
True
>>> string2.isspace( )
False

7. Python String islower()

string.islower( ) 

Returns True all cased characters in the string are lowercase. there must be at least one cased character. It returns False otherwise.


string.islower( ) Example :

>>> string = 'hello'
>>> string2 = 'THERE'
>>> string3 = 'Goldy'
>>> string.islower( )
True
>>> string2.islower( )
False
>>> string3.islower( )
False

8. string.islower( )

string.isupper( )


Tests whether all cased characters in the string are uppercase and requires that there be at least one cased character. Returns True if so and False otherwise.


string.isupper( ) Example :

>>> string = 'HELLO'
>>> string2 = 'There'
>>> string3 = 'goldy'
>>> string.isupper( )
True
>>> string2.isupper( )
False
>>> string3.isupper( )
False

9 Python String lower()

string.lower( )


Returns a copy of the string converted to lowercase.


Example

>>> string.lower( )                  # string = "HELLO"
'hello'

10. Python String upper()

string.upper( )


Returns a copy of the string converted to uppercase.


string.upper( ) Example :

>>> string.upper( )                 # string = "hello"
'HELLO'

11. Python String lstrip()

string.lstrip([chars])


Returns a copy of the string with leading characters removed.
If used without any argument, it removes the leading whitespaces.
One can use the optional chars argument to specify a set of characters to be removed. The chars argument is not a prefix ; rather, all combinations of its values (all possible sub string from the given string argument chars) are stripped when they lead the string.


string.lstrip([chars]) Example :

>>> string2 = 'There'
'There'
>>> string2.lstrip('The')
're'
>>> "saregamapadhanisa".lstrip("tears")
'gamapadhanisa'

12. Python String rstrip()

string.rstrip([chars])

Returns a copy of the string with trailing characters removed.
If used without any argument, it removes the leading whitespaces.
The chars argument is a string specifying the set of characters to be removed.
The chars argument is not a suffix ; rather, all combinations of its values are stripped.


string.rstrip([chars]) Example :

>>> string2 = 'There'
'There'
>>> string2.rstip('care')
'Th'
>>> "saregamapadhanisa".rstrip('tears')
"saregamaphadhani'

lstip( ) function Example

>>> string = "hello"       
>>> string.lstrip( )     <--------- No argument supplied to lstip( ), hence it remove leading whitespaces of the string----->
'hello'
>>> string2 = 'There'
'There'
>>> string2.lstrip('the')
'There'
>>> string2.lstrip('The')
're'
>>> string2.lstrip('he')
'There'
>>> string2.lstrip('Teh')
're'
>>> string2.lstip('heT')
're'

rstrip( ) fuction Example


The rstrip( ) work on identical principle as that of lstrip( ), the only difference is that it matches from right direction.


Consider following examples. We know, you’ll be able to understand if you have carefully read the reasons for lstrip( ) examples.

>>> string = "hello"       
>>> string.rstrip( )     
'hello'
>>> string2 = 'There'
'There'
>>> string2.rstrip('ere')
'Th'
>>> string2.rstrip('care')
'Th'
>>> string2.rstrip('car')
'There'

13. Python String casefold()

The casefold() method is an aggressive lower() method which converts strings to case folded strings for ceaseless matching.

The casefold() method doesn’t take any parameters.

The casefold() method returns the case folded string.

Syntax :

string.casefold()

Example for casefold( )

string = "PYTHON IS AWESOME"

# print lowercase string
print("Lowercase string:", string.casefold())

Output :

Lowercase string: python is awesome

14. Python String center()

The center() method returns a string which is padded with the specified character.

Syntax :

string.center(width[, fillchar])

center() Parameters

The center() method takes two arguments:

  • width – length of the string with padded characters
  • fillchar (optional) – padding character

The fillchar argument is optional. If it’s not provided, space is taken as default argument.

Return Value from center()

The center() method returns a string padded with specified fillchar. It doesn’t modify the original string.

Example : center() Method With Default fillchar

string = "Python is awesome"

new_string = string.center(24)

print("Centered String: ", new_string)

Output :

Centered String:     Python is awesome      

Example : center() Method With * fillchar

string = "Python is awesome"

new_string = string.center(24, '*')

print("Centered String: ", new_string)

Output :

Centered String:  ***Python is awesome****

14. Python String count()

The string count() method returns the number of occurrences of a sub string in the given string.

Syntax :

string.count(substring, start=..., end=...)

String count() Parameters

count() method only requires a single parameter for execution. However, it also has two optional parameters:

  • substring – string whose count is to be found.
  • start (Optional) – starting index within the string where search starts.
  • end (Optional) – ending index within the string where search ends.

count() method returns the number of occurrences of the substring in the given string.

Example : Count number of occurrences of a given substring

# define string
string = "Python is awesome, isn't it?"
substring = "is"

count = string.count(substring)

# print count
print("The count is:", count)

Output :

The count is: 2

Program 1. Program that reads a line and prints its statistics like :


1. Number of uppercase letters :
2. Number of lowercase letters :
3. Number of alphabets :
4. Number of digits :

line = input("Enter a line :")
lowercount = uppercount = 0
digitcount = alphacount = 0
for a in line :
       if a.islower() :
              lowercount += 1
        elif a.isupper() :
              uppercount += 1
         elif a.isdigit() :
               digitcount += 1
         if a.isalpha() :
               alpacount += 1
print("Number of uppercase letters :", uppercount)
print("Number of lowercase letters :", lowercount)
print("Number of alphabets :", alphacount)
print("Number of digits :", digitcount)

sample run of the program is :

Enter a line : Hello 123, ZIPPY zippy zap
Number of uppercase letters : 7            
Number of lowercase letters :  11          
Number of alphabets :  18          
Number of digits : 3

15. Python String encode()

The string encode() method returns encoded version of the given string.

syntax :

string.encode(encoding='UTF-8',errors='strict')

String encode() Parameters

By default, encode() method doesn’t require any parameters.

It returns utf-8 encoded version of the string. In case of failure, it raises a UnicodeDecodeError exception.

Example : Encode to Default Utf-8 Encoding

# unicode string
string = 'pythön!'

# print string
print('The string is:', string)

# default encoding to utf-8
string_utf = string.encode()

# print result
print('The encoded version is:', string_utf)

Output :

The string is: pythön!
The encoded version is: b'pyth\xc3\xb6n!'

Read More :

Python String Methods

Python String Programs

Leave a Reply

Your email address will not be published. Required fields are marked *