
Please support if you like my work by payment through upi: sinhamit@icici or payment by bank
account name: Amit Kumar Sinha,
account number: 2646728782
IFSC code: KKBK0005660
SWIFT: KKBKINBB
String Functions in Category: Python by amit
🕙 Posted on 2023-07-13 at 05:57:42 Read in Hindi ...
String Methods
Everything in Python is an instance of a particular class. The instance of that class is called as an object. You can see in getting help page, that a data-type, for example, print( help( list ) ) statement outputs in first line, class list(object). Also, in different data types page, you can see that output with type() built-in function always returns a class of some data-type, for example, <class 'bool'>, etc.
Functionalities of all functions, (whether built-in, pre-defined, custom,) are same, and these are sometimes named as functions, methods, properties, etc. All these are block of codes, designed and used to perform specific tasks. Methods (or properties, as called in JavaScript) are pre-defined functions, which are specifically applied on an instance of a class or built-in function, that is, str(), etc. There are many pre-defined string methods shown in previous page, by print( dir( str ) ) statement, some of which are explained below.
title(), capitalize(), upper(), lower()
These four string methods are used to change the case of letters (alphabetical characters, from a to z or A to Z), either in uppercase or in lowercase. In following example, 'caMelcaSe stRing' is used to change every letter accordingly when applied with these methods. The output of first two methods in Python are different from that of similar methods or functions in other programming languages.
my_string = 'caMelcaSe stRing'
print( my_string.title() ) # Outputs Camelcase String
print( my_string.capitalize() ) # Outputs Camelcase string
print( my_string.upper() ) # Outputs CAMELCASE STRING
print( my_string.lower() ) # Outputs camelcase string
The title() method applied to a string literal or a variable name (to which that string literal has been assigned), capitalize the first character of each word. But, the capitalize() method, only capitalizes the first character of a string literal. These two methods also lower remaining part of string literal, whether they are uppercase letters. It is unlike behaviour from other programming languages, such as JavaScript, PHP, etc.
print( 'HELLO WORLD'.title() ) # Outputs Hello World
print( 'HELLO WORLD'.capitalize() ) # Outputs Hello world
The upper() method capitalizes each letter (change every letter in uppercase) and the lower() method will convert every letter in lowercase. All of these four methods doesn't take any arguments within the parentheses.
swapcase(), casefold()
print( 'caMelcaSe stRing'.swapcase() ) # Outputs CAmELCAsE STrING
You can see in above example that swapcase() method swaps (flips) the case, that is, uppercase letters are swapped in lowercase, and vice-versa. The casefold() method returns a version of the string suitable for caseless comparisons. This method is similar to lower() method. However, when casefold() is directly applied to a string literal, the lowercase letters are output as shown below. These two methods also doesn't take any arguments within the parentheses.
print( 'caMelcaSe stRing'.casefold() ) # Outputs camelcase string
The casefold() method converts more characters than lower() method, as in the following two examples, the german orthography character ß (derived from a ligature of ⟨ſ⟩ {long s} and ⟨z⟩ {⟨ß⟩; called Eszett "ess-zed/zee" or scharfes S "sharp s"}) is used as string literal. The casefold() method is more stronger, aggresive, and it is used to compare two string literals as described in print( help( str.casefold ) ) documentation.
print( 'ß'.lower() ) # Outputs ß
print( 'ß'.casefold() ) # Outputs ss
In the following example, you can see how both lower() and casefold() methods are applied on long or large string literals. Like docstrings (which is used specifically for documentation purposes), you can also write large strings with \ (backslash) symbol (which is just above the Enter or Return key in your keyboard) in-between that string literal, and placing two single/double quotes, before and after the \ (backslash) symbol.
You can also write a large string as an item (element) of a list data-type without using , (comma) symbol (which is used as separator between two items, or two arguments, or two parameters). You will learn more about list() (in-built function / Class) and its methods, etc. in next page. Like other sequence data-types, you can access an item (or element) from a list with [] (square brackets).
long_string = 'Lorem ipsum dolor sit amet consectetur '\
'adipisicing elit. Harum natus tempore itaque? '\
'Necessitatibus perferendis libero perspiciatis ducimus? '\
'Unde consequuntur, earum, explicabo optio, libero '\
'cumque nihil possimus recusandae delectus laborum maiores?' # This is one string.
print( type( long_string ) ) # Outputs <class 'str'>
print( long_string ) # The above string literal is displayed in one line.
list_item = ['Lorem ipsum dolor sit amet consectetur '
'adipisicing elit. Harum natus tempore itaque? '
'Necessitatibus perferendis libero perspiciatis ducimus? '
'Unde consequuntur, earum, explicabo optio, libero '
'cumque nihil possimus recusandae delectus laborum maiores?'] # This list contains one element (item) which is one string.
print( type( list_item[0] ) ) # Outputs <class 'str'>
print( long_string is list_item[0] ) # Outputs True because id() of both are same
str_lower = long_string.lower()
item_lower = list_item[0].lower()
print( str_lower is item_lower ) # Outputs False because id() of both are different
print( str_lower == item_lower ) # Outputs True because comparison checks letters
str_casefold = long_string.casefold()
item_casefold = list_item[0].casefold()
print( str_casefold is item_casefold ) # Outputs False because id() of both are false
print( str_casefold == item_casefold ) # Outputs True because comparison checks characters
The lower() method converts only ASCII characters to lowercase. But the casefold() method converts both ASCII and non-ASCII characters to lowercase. The lower() method is suitable only for case-insensitive string comparison. But the casefold() method is suitable for both case-sensitive and case-insensitive string comparisons. The lower() method provides high performance than casefold() method which is slower than lower().
istitle(), isupper(), islower()
print( 'Hello World'.istitle() ) # Outputs True
print( 'HELLO WORLD'.isupper() ) # Outputs True
print( 'hello world'.islower() ) # Outputs True
Sometimes, you need to check that user (general public) has entered correct letter-cases (for example, email and website URL should be in lowercase), or some number (for example, age is '32', and not 'thirty-two'), etc. In that situations all these string methods (which prefixed with is) are very helpful. In above three examples, you can see that other cases if used for these above-mentioned methods, then output will be False.
isnumeric(), isdigit(), isdecimal()
print( '12'.isnumeric() ) # Outputs True
print( '12abc'.isnumeric() ) # Outputs False
print( '12'.isdigit() ) # Outputs True
print( '12.5'.isdecimal() ) # Outputs False
isdigit(self, /) − Return True if the string is a digit string, False otherwise. A string is a digit string if all characters in the string are digits and there is at least one character in the string.
isnumeric(self, /) − Return True if the string is a numeric string, False otherwise. A string is numeric if all characters in the string are numeric and there is at least one character in the string.
isdecimal(self, /) Return True if the string is a decimal string, False otherwise. A string is a decimal string if all characters in the string are decimal and there is at least one character in the string.
isalnum(), isalpha()
print( '12abc'.isalnum() ) # Outputs True
print( 'abc'.isalnum() ) # Outputs True
print( '12abc'.isalpha() ) # Outputs False
print( 'abc'.isalpha() ) # Outputs True
Any special characters, such as '=', '+', '-', etc. will output False with above two methods.
Leave a Comment:
Amit Sinha March 2nd, 2023 at 9:30 PM
😃 😄 😁 😆 😅 😂 😉 😊 😇 😍 😘 😚 😋 😜 😝 😶 😏 😒 😌 😔 😪 😷 😵 😎 😲 😳 😨 😰 😥 😢 😭 😱 😖 😣 😞 😓 😩 😫 😤
Ribhu March 3rd, 2023 at 9:30 PM
🐵 🐒 🐶 🐩 🐺 🐱 🐯 🐅 🐆 🐴 🐎 🐮 🐂 🐃 🐄 🐷 🐖 🐗 🐽 🐏 🐑 🐐 🐪 🐫 🐘 🐭 🐁 🐀 🐹 🐰 🐇
