Python Programming – String Functions and Methods

You can learn about Strings in Python Programs with Outputs helped you to understand the language better.

Python Programming – String Functions and Methods

Python provides built-in functions and methods that allow us to do string manipulation. Every string object that you create in python is actually an instance of string calls. The string manipulation methods that are discussed below use the following syntax:
<stringobject>.<method name>( )

len ( )

len() is a built-in function that returns the number of characters in a string.
>>> fruit = ‘ apple ‘
>>> len ( fruit )
5
An empty string contains no chapters and has length O, but other than that, it is the same as any other string.
A string with a length of 1 represents a chapter in python.

a = [‘apple’, ‘banana’, ‘pomegranate’]

for x in a:

print(x, len(x))

str1 = ‘Hello World’

len(str1)

Str1 = ‘Apple is healthy. Apple is also good

for health.’

print ()

print(strl.count(“Apple”))

print ()

str = “elephant”

count = 0

for i in str:

count = count+1

print(count)

capitalize( )

The method capitalize() returns a copy of the string with only its first characters capitalize.
>>> str =” this is string”
>>> str. capitalize()
‘This is string ‘

find( )

The find() method is used to locate the position of the given substring within the string; it returns -1 if it is unsuccessful in finding the substring. find(str, beg=0 end=len(string))
>>> str= “This is a simple sentence”
>>> str.find(‘tan’)
-1
In other words, it returns -1 because a substring is not found in the given string. On omitting the start parameter, the function starts the searching process from the very beginning.

>>> str . find (‘ ten ‘)
20
>>> str. find (‘is,0,4)
2
>>> str. find ( ‘ is, 4,15)
5

isalnum( )

It returns true if string contains only letters and dig-its, i.e., all characters are alphanumeric and false otherwise if the string contains any special character, such as _, @,#,*, including space.
>>>str1=’Work Hard’
>>>strl.isalnum ( )
False
because it has a space which is a special character.
>>>str2 = ‘Work’
>>>str2. isalnum ( )
True

>>>str3=’Work1′
>>>str3.isalnum ( )
True

>>>str4=’ 1234′
>>>str4.isalnum ( )
True

isalpha( )

It returns true if the string contains only letters, otherwise returns false.
>>>str2=’Work’
>>>str2.isalpha( )
True

>>>str3=’Work1′
>>>str3.isalpha( )
False

>>>str4=’ 1234′
>>>str4.isalpha ( )
False

isdigit( )

It returns true if the string contains only digits, and false otherwise.
>>>str2=’Work’
>>>str2.isdigit()
False

>>>str3=’Work1′
>>>str3.isdigit()
False

>>>str4=’1234′
>>>str4.isdigit()
True

lower( )

It converts all the uppercase letters into a string to lowercase.
>>> ‘Save Water’.lower()
save water

islower( )

It returns true if the string is in lowercase, and false otherwise.
>>>str1=’Work Hard’
>>>strl.islower( )
False

>>>str2=’hello’
>>>str2.islower( )
True

>>>Str3 = ‘ROHAN’
>>>str3.islower( )
False

isupper( )

It returns true if the string is in uppercase and false otherwise.
>>>str1=’Work Hard’
>>>str1.isupper()
False

>>>str2=’hello’
>>>str2.isupper( )
False

>>>str3 = ‘ ROHAN’
>>>str3.isupper()
True

upper( )

It returns the exact copy of the string with all letters in uppercase.
>>> ‘Save Water’.upper()
‘SAVE WATER’

lstrip ( )

It removes all the leading (left side) whitespace in a string.
>>> str = ” Save Water”
>>> str.lstrip ( )
‘Save Water’
It removes characters from the left based on the string argument passed (including default white-space characters) and then returns a copy of the string.

>>> str=’ABC International’
>>> print(str)
‘ABC International’

>>> str.lstrip(‘A’)
‘BC International’

>>> str.lstrip(‘ABC ‘)
‘International’

rstrip( )

It returns a copy of the string with trailing characters removed based on the string argument passed. It also removes default whitespace characters from the right.
>>> str2 = “Hello World ”
>>> str2.rstrip()
‘Hello World’
>>> str = “Television”
>>> str.rstrip(‘vision’)
‘Tele’

isspace( )

It returns true if the string contains only whitespace characters, and false otherwise.
>>> ‘ ‘.isspace( )
True
>>> ”.isspace()
False
>>> str=’w’
>>> print(str.isspace())
False

It will return false if the string contains even one character.

istitle( )

It checks whether the string is title-cased, i.e., the first letter of each word is capitalized. It returns true if the string is properly title-cased, and false otherwise.
>>> ‘This Is A Title’.istitle( )
True
>>> ‘This is A title’.istitle( )
False

replace(old,new)

It replaces all occurrences of the old substring in a string with the new substring.
>>> str = ‘This is just a simple string.’
>>> str.replace (‘simple’, ‘short’)
‘This is just a short string.’

>>> ‘This is a test’.replace(‘is’, ‘eez’)
‘Theez eez a test’
The replace() works like a search and replace feature of a word processing software.

split( )
It splits the string according to delimiter str (space, if not provided) and returns a list of substrings, i.e., it splits the string into a list of “words”.
>>> si = “Work is Worship”
>>> words = si.split()
>>> words
[‘Work’, ‘is’, ‘Worship’]

Example
Program to read a line and count number of words.

#Program to read line and count number of words
my_line=input(“Enter a line: “)
x=my_line.split()
count=0
for i in x:
count = count+1
print(count)RUN
>>>
Enter a line: Clean and Green Delhi
4
>>>

Let’s Try

Write the output of the following program to check if “work is worship” or not. the word ‘work’ is present in the string

str = “work is worship”
print (‘work’ in str.split ( ))

join( )

The joinQ method concatenates words from a list of words to form a single string. Elements can be joined using any separator.
>>> str1 = (‘Raja’, ‘Ram’, ‘Mohan’, ‘Rai’)
>>> str1
(‘Raja’, ‘Ram’, ‘Mohan’, ‘Rai’)
>>> str = ‘ ‘
>>> str.join(strl)
‘Raja Ram Mohan Rai’

swapcase( )

It returns a copy of the string with lowercase letters turned into uppercase and vice versa.
>>> str=’COMPUTER’
>>> print(str.swapcase())
computer

>>> str=’computer’
>>> print(str.swapcase())
COMPUTER

partition( )

This function splits the strings at the first occurrence of separator and returns the string in three parts, i.e., before the separator (head), the separator itself, and the part after the separator (tail). If the separator is not found, it returns the string itself, followed by two empty strings.
>>> str = “The Golden Star”
>>> str.partition(‘Gold’)
(‘The ‘, ‘Gold’, ‘en Star’)

>>> str.partition(‘ne’)
(‘The Golden Star’, ”, ”)

>>> str.partition(‘e’)
(‘Th’, ‘e’, ‘ Golden Star’)

str( )

A string is a sequence of one or more characters (letters, numbers, symbols). It is a common form of data in computer programs, and you may need to convert strings into numbers or numbers into strings. You can convert numbers into strings using the str() method. You pass either a number or a variable into the parentheses of the method, and then that numeric value will be converted into a string value. Let us first convert an integer into a string. To convert the integer 17 into a string value, you can pass 17 into the str() method:
>>> str(17)
‘ 17′
The quotes around the number ’17’ signify that the number is no longer an integer but is now a string value. Similarly, when you pass a float into the str() method, the string value of the float will be returned. Strings can be converted to numbers by using the int() and float() methods. int() method converts the strings into integers and allows you to do calculations. You can also convert the numbers to float by using the float ( ) method.

Leave a Reply

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