
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
find(), rfind(), startswith(), endswith() in Category: Python by amit
🕙 Posted on 2023-07-17 at 19:49:24 Read in Hindi ...
More String Methods
In the previous page, you have learned about count(), index(), rindex() methods which not only tell about occurrence and position of sub-string, but also checks whether that sub-string is present in parent string or not. These three string methods also take second and third arguments for starting position (included) and ending position (excluded). These two positions are index number within which sub-string is to be searched.
print( 'Hello World'.count( 'a' ) ) # Outputs 0
print( 'Hello World'.index( 'a' ) ) # Outputs ValueError: substring not found
print( 'Hello World'.rindex( 'a' ) ) # Outputs ValueError: substring not found
However, there are other string methods which can properly check whether any sub-string is present in parent string or not. I have specifically mentioned the output from help() function, when name of each of these methods or built-in functions, is provided as an argument within the parentheses. You should carefully peruse the return type, and return value of these methods or built-in functions, which you will use in programming scripts. See below of this page for details.
find(), rfind()
The find() and rfind() methods checks whether any sub-string is present in the parent string or not, by searching (1) from left to right, and (2) from right to left, respectively. Each of these two methods also takes second and third arguments for starting position (included) and ending position (excluded). These two methods return -1 when the sub-string is not found, otherwise the index number of that sub-string.
print( help( str.find ) )
Help on method_descriptor:
find(...)
S.find(sub[, start[, end]]) -> int
Return the lowest index in S where substring sub is found,
such that sub is contained within S[start:end]. Optional
arguments start and end are interpreted as in slice notation.
Return -1 on failure.
None
print( help( str.rfind ) )
Help on method_descriptor:
rfind(...)
S.rfind(sub[, start[, end]]) -> int
Return the highest index in S where substring sub is found,
such that sub is contained within S[start:end]. Optional
arguments start and end are interpreted as in slice notation.
Return -1 on failure.
None
print( 'Hello World'.find( 'r' ) ) # Outputs 8
print( 'Hello World'.find( 'a' ) ) # Outputs -1
print( 'Hello World'.find( 'l' ) ) # Outputs 2
print( 'Hello World'.find( 'l', 5, 10 ) ) # Outputs 9
print( 'Hello World'.rfind( 'r' ) ) # Outputs 8
print( 'Hello World'.rfind( 'a' ) ) # Outputs -1
print( 'Hello World'.rfind( 'l' ) ) # Outputs 9
print( 'Hello World'.rfind( 'l', 2, 5 ) ) # Outputs 3
If you don't know the position of third argument, in all above string methods, you can also place -1 or -2, etc. (last index number, that is, negative indexing).
startswith(), endswith()
The startswith() and endswith() methods are used to check whether any sub-string is present as prefix or suffix of the parent string. These two methods also take second and third arguments for starting position (included) and ending position (excluded).
print( help( str.startswith ) )
Help on method_descriptor:
startswith(...)
S.startswith(prefix[, start[, end]]) -> bool
Return True if S starts with the specified prefix, False otherwise.
With optional start, test S beginning at that position.
With optional end, stop comparing S at that position.
prefix can also be a tuple of strings to try.
None
print( help( str.endswith ) )
Help on method_descriptor:
endswith(...)
S.endswith(suffix[, start[, end]]) -> bool
Return True if S ends with the specified suffix, False otherwise.
With optional start, test S beginning at that position.
With optional end, stop comparing S at that position.
suffix can also be a tuple of strings to try.
None
print( 'Hello World'.startswith( 'h' ) ) # Outputs False
print( 'Hello World'.startswith( 'H' ) ) # Outputs True
print( 'Hello World'.startswith( 'He' ) ) # Outputs True
print( 'Hello World'.startswith( 'Wo', 6, 10 ) ) # Outputs True
print( 'Hello World'.endswith( 'd' ) ) # Outputs True
print( 'Hello World'.endswith( 'D' ) ) # Outputs False
print( 'Hello World'.endswith( 'ld' ) ) # Outputs True
print( 'Hello World'.endswith( 'o', 2, 5 ) ) # Outputs True
Return Type & Return Value
Till now, you have see various built-in functions, and methods for some of these built-in functions. Some functions and methods may take many arguments, such as print() can take many arguments within the parentheses, separated by , (comma). Other functions and methods exactly take only one argument, such as input(), type(), len(), etc. Mostly, functions and methods take fixed number of arguments, as you can see in above examples, some of which are optional.
Python 3.10.9 (tags/v3.10.9:1dd9be6, Dec 6 2022, 20:01:21) [MSC v.1934 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> help( print )
Help on built-in function print in module builtins:
print(...)
print(value, ..., sep=' ', end='\n', file=sys.stdout, flush=False)
Prints the values to a stream, or to sys.stdout by default.
Optional keyword arguments:
file: a file-like object (stream); defaults to the current sys.stdout.
sep: string inserted between values, default a space.
end: string appended after the last value, default a newline.
flush: whether to forcibly flush the stream.
You can see in above description that print() function has no returned value. Many parameters in any function, method or those in other modules, are of advanced uses. You can see in above description, that print() function has other parameters after value, ..., , which are unnecessary for beginners, and thus, overwhelm you.
print( help( print ) ) # Herein, print inside help() will display the same OUTPUT as shown above. The outer print() function executes the help( print ) statement.
print( help( type ) ) # first few lines of OUTPUT are shown herein below:
class type(object)
| type(object) -> the object's type
| type(name, bases, dict, **kwds) -> a new type
|
| Methods defined here:
|
Output of some functions cannot be used as returned value, such as print() and type(). But, other functions and methods generally, output specific data-type literals (return type), that is, len() returns integer data-type, input() returns string data-type. The output from the input() function must always be type-casted with int() or float() built-in function, before using in arithematic operations.
x = type( 'hello' )
print( x, type( x ) ) # Outputs <class 'str'> <class 'type'>
y = len( 'hello' )
print( y, type( y ) ) # Outputs 5 <class 'int'>
z = input( 'Write something: ' )
print( type( z ) ) # Outputs <class 'str'>
String Methods Return Types & Return Values
You should be very careful while using any method of a specific built-in function, for example, str(). The str() function itself returns a string data-type, of the argument passed to it. In the following table, you can see that different methods or functions which can return same data-type, but the returned value will be different, depending on expressions (statements) passed as arguments inside the parentheses. For example, -1 is not index number, when find() or rfind() does not find the sub-string into the parent string.
my_var = str( 123 )
print( my_var, type( my_var ) ) # Outputs 123 <class 'str'>
| method/ | returned type | returned value |
|---|---|---|
| len() | int | total number of characters or items in a container |
| count() | int | non-overlapping occurrences of sub-string |
| index() | int | index number (positive) or ValueError |
| rindex() | int | index number (positive) or ValueError |
| find() | int | index number (positive) or -1 (when not found) |
| rfind() | int | index number (positive) or -1 (when not found) |
| startswith | bool | True or False |
| endswith | bool | True or False |
| title() | str | First letter of each word in uppercase, and other characters in lowercase. |
| capitalize() | str | First letter of parent string in uppercase, and other characters in lowercase. |
| upper() | str | All letters of parent string in uppercase. |
| lower() | str | All letters of parent string in lowercase. |
| swapcase() | str | All letters of parent string are swapped (flipped) in opposite case. |
| casefold() | str | All letters of parent string are converted into lowercase. |
| istitle() | bool | True or False |
| isupper() | bool | True or False |
| islower() | bool | True or False |
| isnumeric() | bool | True or False |
| isdigit() | bool | True or False |
| isdecimal() | bool | True or False |
| isalnum() | bool | True or False |
| isalpha() | bool | True or False |
You should always remember what data-type is returned from a function or method, and also what value is received from such operation, expression, or statement. An integer value, for example, 9 can be index number in a parent string, and therefore it should not be treated/
Leave a Comment:
Amit Sinha March 2nd, 2023 at 9:30 PM
😃 😄 😁 😆 😅 😂 😉 😊 😇 😍 😘 😚 😋 😜 😝 😶 😏 😒 😌 😔 😪 😷 😵 😎 😲 😳 😨 😰 😥 😢 😭 😱 😖 😣 😞 😓 😩 😫 😤
Ribhu March 3rd, 2023 at 9:30 PM
🐵 🐒 🐶 🐩 🐺 🐱 🐯 🐅 🐆 🐴 🐎 🐮 🐂 🐃 🐄 🐷 🐖 🐗 🐽 🐏 🐑 🐐 🐪 🐫 🐘 🐭 🐁 🐀 🐹 🐰 🐇
