Detailed explanation of the usage of startswith of and endswith of in python

  • 2021-12-11 07:45:14
  • OfStack

startswith () method

The Python startswith () method checks whether a string begins with a specified substring
If yes, True is returned, otherwise False is returned. If the parameters beg and end specify values, check within the specified range.
str.startswith(str, beg=0,end=len(string));

Parameter

str--The detected string. strbeg--Optional to set the starting position of string detection. strend--Optional to set the end position of string detection.

Return value

Returns True if a string is detected, and False otherwise.

Common environment: Used for IF judgment


listsql = 'select * from ifrs.indiv_info'
def isSelect(sql):
    chsql = sql.upper().strip()
    if not chsql.startswith("SELECT "):
        return False
    return True

print isSelect(listsql)
[root@bigdata-poc-shtz-3 zw]# python h.py
True

endswith () method

Function: Determine whether a string ends with a specified character or substring, which is often used to determine the file type

Function description

Syntax:


string.endswith(str, beg=[0,end=len(string)])
string[beg:end].endswith(str)

Parameter description:

string:--Detected string str:--The specified character or substring (tuples can be used, matching one by one) beg:--Sets the starting position of string detection (optional, from the left) end:--Sets the end position of string detection (optional, from the left) If there are parameters beg and end, check within the specified range, otherwise check in the whole string

Return value:

If a string is detected, True is returned, otherwise False is returned.

Parsing: Returns True if the string string ends with str, otherwise returns False

Note: Null characters are considered true


'''
 No one answers the problems encountered in study? Xiaobian created 1 A Python Learning and communication group: 531509025
 Looking for like-minded friends and helping each other , There are also good video learning tutorials and PDF E-books! 
'''
>>> endsql = 'select * from ifrs.indiv_info'
>>> endsql.endswith('info')
True
>>> endsql.endswith('info',3)
True
>>>
>>> endsql.endswith('info',3,10)
False
>>> endsql.endswith('info',25,29)
True
>>> endsql.endswith('')
True

Common environment: used to judge file types (such as pictures and executable files)


>>> f = 'a.txt'
>>> if f.endswith(('.txt')):
...  print '%s is a txt' %f
... else:
...  print '%s is not a txt' %f
...
a.txt is a txt

Related articles: