Python text ends with

Python String endswith()

The endswith() method returns True if a string ends with the specified suffix. If not, it returns False .

Example

message = 'Python is fun' 
# check if the message ends with fun print(message.endswith('fun'))
# Output: True

Syntax of String endswith()

The syntax of endswith() is:

str.endswith(suffix[, start[, end]])

endswith() Parameters

The endswith() takes three parameters:

  • suffix — String or tuple of suffixes to be checked
  • start (optional) — Beginning position where suffix is to be checked within the string.
  • end (optional) — Ending position where suffix is to be checked within the string.

Return Value from endswith()

The endswith() method returns a boolean.

  • It returns True if a string ends with the specified suffix.
  • It returns False if a string doesn’t end with the specified suffix.

Example 1: endswith() Without start and end Parameters

text = "Python is easy to learn." 
result = text.endswith('to learn')
# returns False print(result)
result = text.endswith('to learn.')
# returns True print(result)
result = text.endswith('Python is easy to learn.')
# returns True print(result)

Example 2: endswith() With start and end Parameters

text = "Python programming is easy to learn." # start parameter: 7 # "programming is easy to learn." string is searched 
result = text.endswith('learn.', 7)
print(result) # Both start and end is provided # start: 7, end: 26 # "programming is easy" string is searched
result = text.endswith('is', 7, 26)
# Returns False print(result)
result = text.endswith('easy', 7, 26)
# returns True print(result)

Passing Tuple to endswith()

It’s possible to pass a tuple suffix to the endswith() method in Python.

Читайте также:  Selenium safari driver python

If the string ends with any item of the tuple, endswith() returns True . If not, it returns False

Example 3: endswith() With Tuple Suffix

text = "programming is easy" 
result = text.endswith(('programming', 'python'))
# prints False print(result)
result = text.endswith(('python', 'easy', 'java'))
#prints True print(result) # With start and end parameter # 'programming is' string is checked
result = text.endswith(('is', 'an'), 0, 14)
# prints True print(result)

If you need to check if a string starts with the specified prefix, you can use startswith() method in Python.

Источник

Метод endwith() в Python

Метод endwith() возвращает True, если строка заканчивается указанным суффиксом. Если нет, возвращается False.

str.endswith(suffix[, start[, end]])

Параметры

endwith() принимает три параметра:

  • суффикс ‒ строка или кортеж суффиксов для проверки;
  • start (необязательно) ‒ начальная позиция, в которой следует проверить суффикс в строке;
  • end (необязательно) ‒ конечная позиция, в которой следует проверить суффикс в строке.

Возвращаемое значение

Метод возвращает логическое значение:

  • Он возвращает True, если строки заканчиваются указанным суффиксом.
  • Он возвращает False, если строка не заканчивается указанным суффиксом.

Пример 1: Без начальных и конечных параметров

text = "Python is easy to learn." result = text.endswith('to learn') # returns False print(result) result = text.endswith('to learn.') # returns True print(result) result = text.endswith('Python is easy to learn.') # returns True print(result)

Пример 2: С параметрами start и end

text = "Python programming is easy to learn." # start parameter: 7 # "programming is easy to learn." string is searched result = text.endswith('learn.', 7) print(result) # Both start and end is provided # start: 7, end: 26 # "programming is easy" string is searched result = text.endswith('is', 7, 26) # Returns False print(result) result = text.endswith('easy', 7, 26) # returns True print(result)

Передача кортежа

В Python можно передать суффиксы кортежа.

Если строка заканчивается каким-либо элементом кортежа, endwith() возвращает True. Если нет, возвращается False.

Пример 3: С суффиксом кортежа

text = "programming is easy" result = text.endswith(('programming', 'python')) # prints False print(result) result = text.endswith(('python', 'easy', 'java')) #prints True print(result) # With start and end parameter # 'programming is' string is checked result = text.endswith(('is', 'an'), 0, 14) # prints True print(result)

Если вам нужно проверить, начинается ли строка с указанного префикса, вы можете использовать метод startswith() в Python.

Источник

Python String endswith: Check if String Ends With Substring

Python String endswith Check if String Ends With Substring Cover Image

The Python endswith method is used to check if a string ends with a specific substring. In this tutorial, you’ll learn how to use the Python endswith method to evaluate whether a string ends with one or more substrings. Being able to check if a string ends with another string allows you to, for example, check the extension of a file or the type of email domain. Alternatively, you can use the startswithmethod to check if a string starts with a substring.

By the end of this tutorial, you’ll have learned:

  • How to use the Python endswith() function to check if a string ends with a substring
  • How to use the Python endswith () function with multiple strings
  • How to use the Python endswith () function without case sensitivity
  • How to use the Python endswith () function with a list of strings

Understanding the Python endswith Function

Before diving into how to use the Python endsswith() function, it’s important to understand the syntax of the function. The code block below breaks down the different required and optional parameters that the function has to offer.

# Understanding the Python endswith() Function str.endswith(prefix, start, end)

The table below breaks down the parameters of the function as well as any default arguments that the function provides:

Источник

Python String endswith() Method

Check if the string ends with a punctuation sign (.):

txt = «Hello, welcome to my world.»

Definition and Usage

The endswith() method returns True if the string ends with the specified value, otherwise False.

Syntax

Parameter Values

Parameter Description
value Required. The value to check if the string ends with
start Optional. An Integer specifying at which position to start the search
end Optional. An Integer specifying at which position to end the search

More Examples

Example

Check if the string ends with the phrase «my world.»:

txt = «Hello, welcome to my world.»

Example

Check if position 5 to 11 ends with the phrase «my world.»:

txt = «Hello, welcome to my world.»

x = txt.endswith(«my world.», 5, 11)

Unlock Full Access 50% off

COLOR PICKER

colorpicker

Join our Bootcamp!

Report Error

If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:

Thank You For Helping Us!

Your message has been sent to W3Schools.

Top Tutorials
Top References
Top Examples
Get Certified

W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookie and privacy policy.

Источник

Python String endswith() Method

The python string endswith() method checks if the input string ends with the specified suffix. This function returns true if the string ends with the specified suffix, otherwise returns false.

This function has one mandatory parameter and two optional parameters. The mandatory parameter is a string that needs to be checked and optional parameters are the start and end indexes. By default, the start index is 0 and the end index is length -1.

In the following section, we will be learning more details about the python string endswith() method.

Syntax

The following is the syntax for the python string endswith() method.

str.endswith(suffix[, start[, end]])

Parameters

The parameters of the python string endswith() method are as follows.

  • suffix − This parameter specifies a string or a tuple of suffixes to look for.
  • start − This parameter specifies the starting index to search.
  • end − This parameter specifies the ending index where the search ends.

Return Value

The python string endswith() method returns true if the string ends with the specified suffix and otherwise, it returns false.

Example

The python string endswith() method applied on a string with a suffix as its parameter will return a boolean value true if the string ends with that suffix. Else, it returns false.

The following is an example in which a string «Hello!Welcome to Tutorialspoint.» is created and the suffix ‘oint’ is also specified. Then, endswith() function is invoked on the string with only the suffix as its argument and the result is printed as output using the print() function.

#!/usr/bin/python str = "Hello!Welcome to Tutorialspoint."; suffix = "oint."; result=str.endswith(suffix) print("The input string ends with the given suffix:", result)

On executing the above program, the following output is generated —

The input string ends with the given suffix: True

Example

The python string endswith() method applied on a string with a suffix, start index as its parameters will return a boolean value true if the string ends with that suffix and starts from the specified start index. Else, it returns false.

The following is an example in which a string «Hello!Welcome to Tutorialspoint.» is created and the suffix ‘oint’ is also specified. Then, endswith() function is invoked on the string with the suffix and the start index ’28’ passed as its arguments and the result is printed as output using the print() function.

#!/usr/bin/python str = "Hello!Welcome to Tutorialspoint."; suffix = "oint."; result=str.endswith(suffix, 28) print("The input string ends with the given suffix:",result)

The following is the output obtained by executing the above program —

The input string ends with the given suffix: False

Example

The python string endswith() method applied on a string with a suffix, start index and end index as its parameters will return a boolean value true if the string ends with that suffix in the given range. Else, it returns false.

The following is an example in which a string «Hello!Welcome to Tutorialspoint.» is created and the suffix ‘oint.’ is also specified. Then, endswith() function is invoked on the string with the suffix, the start as ’27’ and the end index as ’32’ passed as its arguments and the result is printed as output using the print() function.

#!/usr/bin/python str = "Hello!Welcome to Tutorialspoint."; suffix = "oint."; result=str.endswith(suffix, 27, 32) print("The input string ends with the given suffix:",result)

The above program, on executing, displays the following output —

The input string ends with the given suffix: True

Example

The python string endswith() method’s first parameter must be in the form of a string which specifies the suffix that is to be checked in the input string. If the string is not specified in its parameter, a type error is occured.

The following is an example in which a string «Hello!Welcome to Tutorialspoint.» is created and then, endswith() function is invoked on the string and the start index as ’27’ and the end index as ’32’ is passed as its arguments and the result is printed as output using the print() function.

#!/usr/bin/python str = "Hello!Welcome to Tutorialspoint."; result=str.endswith(27, 32) print("The input string ends with the given suffix:",result)

The following is the output displayed on executing the above program —

Traceback (most recent call last): File "main.py", line 2, in result=str.endswith(27, 32) TypeError: endswith first arg must be str or a tuple of str, not int

Example

The python string endswith method takes atleast one argument. If no arguments are specified, then a type error is occured.

The following is an example in which a string «Hello!Welcome to Tutorialspoint.» is created and then, endswith() function is invoked on the string with no arguments passed and the result is printed as output using the print() function.

#!/usr/bin/python str = "Hello!Welcome to Tutorialspoint."; result=str.endswith() print("The input string ends with the given suffix:",result)

The output of the above program is displayed as follows —

Traceback (most recent call last): File "main.py", line 2, in result=str.endswith() TypeError: endswith() takes at least 1 argument (0 given)

Источник

Оцените статью