Python Programming – String Functions

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

Python Programming – String Functions

Python has several built-in functions associated with the string data type. These functions let us easily modify and manipulate strings. Every string object that you create in Python is actually an instance of the String class. Most of the string manipulation methods are already discussed in chapter 6. Syntax
<stringObject>.<method name>( )

count ( )

count( ) returns the number of times a specified value occurs in a 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.

rfind ( )

Searches the string for a specified value and returns the last position of where it was found.

capitalize ( )

The method capitalize ( ) returns a copy of the string with only its first character capitalized.

title ( )

The method title ( ) converts the first character of each word to uppercase.

lower ( )

It converts all the uppercase letters in a string to lowercase.

upper ( )

It returns the exact copy of the string with all letters in uppercase.

swapcase ( )

It returns a copy of the string with lowercase letters turned into uppercase and vice-versa.

islower ( )

It returns true if the string is in lowercase and false otherwise.

isupper ( )

It returns true if the string is in uppercase and false otherwise.

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.

replace(old,new)

It replaces all occurrences of the old substring in a string with the new substring.

strip ( )

It removes whitespaces from the start and end of the string.

lstrip ( )

It removes all the leading (left side) whitespace in a string.

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.

split ( )

The split method returns a list of the words of a string. The method assumes that words are separated by whitespace, which can be either spaces, tabs, or newline characters.

partition ( )

This function splits the strings at the first occurrence of the 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.

join ( )

The join ( ) method takes a list of strings and joins them together into a single string. Elements can be joined using any separator.

isspace ( )

It returns true if the string contains only whitespace characters, and false otherwise.

isalpha ( )

It returns true if the string contains only letters, otherwise returns false.

isdigit ( )

It returns true if the string contains only digits, and false otherwise.

isalnum ( )

It checks whether the string consists of only alphanu¬meric characters.

startswith ( )

The startswith ( ) check whether that string starts with a particular string and returns true if the string starts with the specified string, i.e., it determines if the string is a prefix of the string.
>>> str1=’Work Hard’
>>> str1.startswith(‘Work’)
True
Note that startswith requires case to match.
>>> str1=’Work Hard’
>>> str1.startswith(‘work’)
False

endswith ( )

endswith() check whether that string ends with a . particular string and returns true if the string ends with the specified string, i.e., it determines if the string is a suffix of the string.
>>> str1=’Work Hard’
>>> strl.endswith(‘Hard’)
True
>>> strl.endswith(‘hard’)
False

encode ( ) and decode ( )

The encode ( ) and decode ( ) methods are used to transform string data to and from a specified character encoding. As input, these accept an encoding name such as ‘ascii’, ‘utf-8’, or ‘utf-16′. These strings into a data encoding suitable for I/O operations. The encode ( ) method is only available on strings, and the decoder ( ) method is only available on the bytes datatype.
>>> str1=’Hello World’
>>> str1.encode()
b’Hello World’
Note that literal b is added in front of a string declaration, for creating a bytes object.

str ( )

str ( ) takes an argument and returns the string equivalent of it.

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”.

String Slicing

Slicing is a string operation for extracting a part of the string. To extract a single character from a string, follow the string with the index of the desired character surrounded by square brackets ([ ]), remembering that the first character of a string has index zero. The syntax is s[i:j] meaning the substring starting at index i, running up to but not including index j.

Example
Demo of string slicing.

MyString = “ABCDEF”
print(MyString) # Prints a whole string.
print(MyString[0:3]) # Prints characters 0 to 3.
print(MyString[3::]) # Prints from character 3 to the end.
print(MyString[0:6:2]) #Prints every alternate character.
print(MyString[-1:-7:-1]) #Prints every character backwards
print(MyString[0:-2]) #Print until -2 from the end.RUN
>>>
ABCDEF
ABC
DEF
ACE
FEDCBA
ABCD
>>>

Membership
Membership operator in; returns true if a character exists in the given string, false otherwise.

Leave a Reply

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