Python if text starts with

Метод startswith() в Python

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

str.startswith(prefix[, start[, end]])

Параметры

Метод в Python принимает не более трех параметров:

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

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

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

Пример 1: Без параметров start и end

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

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

text = "Python programming is easy." # start parameter: 7 # 'programming is easy.' string is searched result = text.startswith('programming is', 7) print(result) # start: 7, end: 18 # 'programming' string is searched result = text.startswith('programming is', 7, 18) print(result) result = text.startswith('program', 7, 18) print(result)

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

В Python можно передать кортеж префиксов в метод startswith(). Если строка начинается с любого элемента кортежа, команда возвращает True. Если нет, возвращается False.

Читайте также:  Java immutable object is modified

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

text = "programming is easy" result = text.startswith(('python', 'programming')) # prints True print(result) result = text.startswith(('is', 'easy', 'java')) # prints False print(result) # With start and end parameter # 'is easy' string is checked result = text.startswith(('programming', 'easy'), 12, 19) # prints False print(result)

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

Источник

Python String startswith()

The startswith() method returns True if a string starts with the specified prefix(string). If not, it returns False .

Example

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

Syntax of String startswith()

The syntax of startswith() is:

str.startswith(prefix[, start[, end]])

startswith() Parameters

startswith() method takes a maximum of three parameters:

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

startswith() Return Value

startswith() method returns a boolean.

  • It returns True if the string starts with the specified prefix.
  • It returns False if the string doesn’t start with the specified prefix.

Example 1: startswith() Without start and end Parameters

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

Example 2: startswith() With start and end Parameters

text = "Python programming is easy." # start parameter: 7 # 'programming is easy.' string is searched 
result = text.startswith('programming is', 7)
print(result) # start: 7, end: 18 # 'programming' string is searched
result = text.startswith('programming is', 7, 18)
print(result)
result = text.startswith('program', 7, 18)
print(result)

Passing Tuple to startswith()

It’s possible to pass a tuple of prefixes to the startswith() method in Python.

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

Example 3: startswith() With Tuple Prefix

text = "programming is easy" 
result = text.startswith(('python', 'programming'))
# prints True print(result)
result = text.startswith(('is', 'easy', 'java'))
# prints False print(result) # With start and end parameter # 'is easy' string is checked
result = text.startswith(('programming', 'easy'), 12, 19)
# prints False print(result)

If you need to check if a string ends with the specified suffix, you can use endswith() method in Python.

Источник

Python String startswith() Method

The Python string method startswith() checks whether string starts with a given substring or not. This method accepts a prefix string that you want to search for and is invoked on a string object.

The method can also limit the search range by defining the indices where the search begins and ends, i.e. the user can decide where in the string can start the search and terminate it. So, even if the substring does not start the string, but it begins from the specified limit set, the method returns true.

Syntax

Following is the syntax for Python String startswith() method −

str.startswith(str, beg=0,end=len(string));

Parameters

  • str − This is the string to be checked.
  • beg − This is the optional parameter to set start index of the matching boundary.
  • end − This is the optional parameter to end start index of the matching boundary.

Return Value

This method returns true if found matching string otherwise false.

Example

Without passing optional parameters, the method checks whether the string input starts with the substring parameter passed. If yes, it returns true.

The following example shows the usage of Python String startswith() method. Here, we are creating a string «this is string example. wow. » and call the startswith() method on it. We pass a substring to the method as its argument and record the return value as follows —

#!/usr/bin/python str = "this is string example. wow. "; print str.startswith( 'this' ) print str.startswith( 'is' )

When we run above program, it produces following result −

Example

When we pass a substring and optional (start, end) parameters to the method, it returns true if the string input starts with the given substring from the given start index.

In this example, we create a string «this is string example. wow. «. Then, we call the startswith() method on it. We pass the substring, start and end arguments to it as follows −

str = "this is string example. wow. "; print str.startswith( 'this', 3, 10 ) print str.startswith( 'is', 2, 8 )

When we run above program, it produces following result −

Example

In the following example, we create two strings str1 = «Hello Tutorialspoint» and str2 = «Hello». Using conditional statements, we check the return value of the startswith() method, called on string str1 by passing string str2 as the argument to it.

str1 = "Hello Tutorialspoint" str2 = "Hello" if str1.startswith(str2): print("The string starts with " + str2) else: print("The string does not start with " + str2)

When we run above program, it produces following result −

The string starts with Hello

Example

In the following example we pass the substring and optional parameters, to compare with the input string; and using conditional statements, we print the return value.

str1 = "Tutorialspoint" str2 = "Tutorials" if str1.startswith(str2): print("The string starts with " + str2) else: print("The string does not start with " + str2)

When we run above program, it produces following result −

The string does not start with Tutorials

Источник

Python String startswith: Check if String Starts With Substring

Python String startswith Check if String Starts With Substring Cover Image

The Python startswith method is used to check if a string starts with a specific substring. In this tutorial, you’ll learn how to use the Python startswith function to evaluate whether a string starts with one or more substrings. Being able to check if a string starts with another string is a useful way to check user input, such as for phone numbers or names. Alternatively, you can use the startswithmethod to check if a string ends with a substring.

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

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

Understanding the Python startswith Function

Before diving into how to use the Python startswith() function, it’s essential 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 startswith() Function str.startswith(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 startswith() Method

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

Syntax

Parameter Values

Parameter Description
value Required. The value to check if the string starts 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 position 7 to 20 starts with the characters «wel»:

txt = «Hello, welcome to my world.»

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.

Источник

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