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
removeprefix(), removesuffix(), split(), rsplit(), splitlines(), strip(), lstrip(), rstrip() in Category: Python by amit
🕙 Posted on 2023-07-21 at 03:06:16 Read in Hindi ...
More String Methods
By executing print( dir( str ) ), print( dir( bytearray ) ), and print( dir( bytes ) ), you can see that among many other methods, following methods' name are exactly same, except encode()
and decode()
methods, till zfill(). Many of these similar methods for different data-types have similar functionalities.
string: 'capitalize', 'center', 'count', 'encode', 'endswith', 'expandtabs', 'find', 'index', 'isalnum', 'isalpha', 'isascii', 'isdigit', 'islower', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'maketrans', 'partition', 'removeprefix', 'removesuffix', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill', 'casefold', 'format', 'format_map', 'isdecimal', 'isidentifier', 'isnumeric', 'isprintable'
bytearray: 'capitalize', 'center', 'count', 'decode', 'endswith', 'expandtabs', 'find', 'index', 'isalnum', 'isalpha', 'isascii', 'isdigit', 'islower', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'maketrans', 'partition', 'removeprefix', 'removesuffix', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill', 'append', 'clear', 'copy', 'extend', 'fromhex', 'hex', 'insert', 'pop', 'remove', 'reverse'
bytes: 'capitalize', 'center', 'count', 'decode', 'endswith', 'expandtabs', 'find', 'index', 'isalnum', 'isalpha', 'isascii', 'isdigit', 'islower', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'maketrans', 'partition', 'removeprefix', 'removesuffix', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill', 'fromhex', 'hex'
You have already learned about many string methods (which are also for other data-types), in previous pages. Let's learn some more string methods:
removeprefix(), removesuffix()
You can get help documentation, by executing print( help( str.removeprefix ) ) and print( help( str.removesuffix ) ) statements. See below table for details.
Sometimes, you have to ask user (public) to input
something specific, such as, (1) add a note, (2) edit the note, (3) delete the note, (4) display the note, etc. (for example) in the simple CLI app, we will build later. In such situations, you can either ask the user to enter commands separately, or simultaneously, while writing or interacting with notes.
You have various options, such as by slicing, you can achieve the result. Or, you can use removeprefix()
and removesuffix()
methods for these actions. In following four examples, the string literal 'add new item' is applied with these two methods, and required sub-string 'add ' or ' item' (along with blank space, after or before, which may not be necessary) is passed as an argument. When the sub-string is not found in the parent string (blank space is also included, when provided as part of the (sub-string) argument), the original string is returned as OUTPUT.
print( 'add new item'.removeprefix( 'add ' ) ) # Outputs new item
print( 'add new item'.removeprefix( ' item' ) ) # Outputs add new item
print( 'add new item'.removesuffix( 'add ' ) ) # Outputs add new item
print( 'add new item'.removesuffix( ' item' ) ) # Outputs add new
split(), rsplit(), splitlines()
You can get help documentation, by executing print( help( str.split ) ) , print( help( str.rsplit ) ) and print( help( str.splitlines ) ) statements. See below table for details. These three string methods returns list data-type. The split()
and rsplit()
methods take two arguments: (1) a sub-string (separator), for example, ' ' a blank-(white) space (by default, also \n (new line) \r (carriage return) \t (tab) \f (line-feed)), two or more blank spaces, comma, or any other symbol, etc. within a pair of double/
my_string = 'Hello,
my_list = my_string.split( ',' )
# Four items in the list created, second argument is not provided in above line.
print( my_list ) # Outputs ['Hello', 'World', 'Morning', 'Welcome']
print( len( my_list ) ) # Outputs 4
new_list = my_string.split( ',', 2 )
# Three items in the list created, only first two commas are treated as separator.
print( new_list ) # Outputs ['Hello', 'World', 'Morning,Welcome']
print( len( new_list ) ) # Outputs 3
In the above example, the string literal 'Hello,
print( 'Hello World'.split() ) # Outputs ['Hello', 'World']
print( 'Hello , World , Morning , Welcome'.split( ',' ) ) # Outputs ['Hello ', ' World ', ' Morning ', ' Welcome']
In the above example, you can see that white-(blank) spaces are preserved, and placed inside the pair of single quotes, of every item/
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?' # To create multi-line long string, see previous page
list_created = long_string.split()
print( list_created ) # Outputs each word as an item/
print( len( list_created ) ) # Outputs 30
30
print( long_string ) will output a long single-line string, because there is no line-break in the string literal, but that string literal is written in multi-lines. The splitlines()
method splits the long strings with \n (new line escape character) at every line break (or new line) is inserted.
long_string = 'Lorem ipsum dolor sit amet\nconsectetur '\
'adipisicing elit.\nHarum natus tempore itaque?\n'\
'Necessitatibus perferendis libero\nperspiciatis ducimus? '\
'Unde consequuntur,\nearum, explicabo optio, libero\n'\
'cumque nihil possimus recusandae\ndelectus laborum maiores?'
print( len( long_string.split() ) ) # Outputs 30 because at some blank spaces, new line escape character is added.
list_created = long_string.splitlines()
print( list_created ) # Outputs each line, where \n is inserted, as an item/
print( len( list_created ) ) # Outputs 8
['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?']
8
The splitlines()
method takes only one argument, that is keepends = True or simply, True (by default, it is False). In the above example, the boolean value is not provided within the parentheses, and thus, escape character, \n is not preserved. But, when True is passed as an argument inside splitlines()
method, that is, splitlines( keepends = True ) or splitlines( True ) the output will be different, and as follows:
['Lorem ipsum dolor sit amet\n', 'consectetur adipisicing elit.\n', 'Harum natus tempore itaque?\n', 'Necessitatibus perferendis libero\n', 'perspiciatis ducimus? Unde consequuntur,\n', 'earum, explicabo optio, libero\n', 'cumque nihil possimus recusandae\n', 'delectus laborum maiores?']
8
The split()
and splitlines()
methods splits the parent string, starting from left to right. But the rsplit()
method splits the parent string, starting from right to left.
my_string = 'Hello,
my_list = my_string.rsplit( ',' )
# Four items in the list created, second argument is not provided in above line.
print( my_list ) # Outputs ['Hello', 'World', 'Morning', 'Welcome']
print( len( my_list ) ) # Outputs 4
new_list = my_string.rsplit( ',', 2 )
# Three items in the list created, only last two commas are treated as separator.
print( new_list ) # Outputs ['Hello,World', 'Morning', 'Welcome']
print( len( new_list ) ) # Outputs 3
strip(), lstrip(), rstrip()
You can get help documentation, by executing print( help( str.strip ) ) , print( help( str.lstrip ) ) and print( help( str.rstrip ) ) statements. See below table for details. The strip()
method removes any (one or more) blank (white-) spaces which are before (leading) and after (trailing) the parent string.
Similarly, lstrip()
method only removes any blank (white-) spaces before (leading) parent string. And, rstrip()
method only removes any blank (white-) spaces after (trailing) parent string. These three methods don't remove any white- (blank) space which is in between two characters.
print( ' Hello World '.strip() ) # Outputs Hello World
print( ' Hello World '.lstrip() ) # Outputs Hello World
print( ' Hello World '.rstrip() ) # Outputs Hello World
Though white-(blank) spaces left behind the last character, is not visible (in CLI or VSCode Editor Terminal) by us, it can be selected and counted.
method/ | returned type | returned value |
---|---|---|
removeprefix(self, prefix, /) | str | Return a str with the given prefix string removed if present. If the string starts with the prefix string, return string[len(prefix):]. Otherwise, return a copy of the original string. |
removesuffix(self, suffix, /) | str | Return a str with the given suffix string removed if present. If the string ends with the suffix string and that suffix is not empty, return string[:-len(suffix)]. Otherwise, return a copy of the original string. |
split(self, /, sep=None, maxsplit=-1) | list | Return a list of the substrings in the string, using sep as the separator string. When set to None (the default value), will split on any whitespace character (including \\n \\r \\t \\f and spaces) and will discard empty strings from the result. |
rsplit(self, /, sep=None, maxsplit=-1) | list | (Same as described above for split() method, but) Splitting starts at the end of the string and works to the front. |
splitlines(self, /, keepends=False) | list | Return a list of the lines in the string, breaking at line boundaries. Line breaks are not included in the resulting list unless keepends is given and true. |
strip(self, chars=None, /) | str | Return a copy of the string with leading and trailing whitespace removed. |
lstrip(self, chars=None, /) | str | Return a copy of the string with leading whitespace removed. |
rstrip(self, chars=None, /) | str | Return a copy of the string with trailing whitespace removed. |
The join()
, format()
methods, and also f""
or f''
(known as f-string ) are also used to concatenate two or more strings and other data-type literals. You will learn about format()
, f-string and other string methods in next page.
Leave a Comment:
Amit Sinha March 2nd, 2023 at 9:30 PM
😃 😄 😁 😆 😅 😂 😉 😊 😇 😍 😘 😚 😋 😜 😝 😶 😏 😒 😌 😔 😪 😷 😵 😎 😲 😳 😨 😰 😥 😢 😭 😱 😖 😣 😞 😓 😩 😫 😤
Ribhu March 3rd, 2023 at 9:30 PM
🐵 🐒 🐶 🐩 🐺 🐱 🐯 🐅 🐆 🐴 🐎 🐮 🐂 🐃 🐄 🐷 🐖 🐗 🐽 🐏 🐑 🐐 🐪 🐫 🐘 🐭 🐁 🐀 🐹 🐰 🐇