Python Programs | IT Developer
IT Developer

Python Programs



Share with a Friend

Python Programs - Conditional Statements

Check if a string starts with a specific letter - Python Program

Example 1 :

s = input("Enter a string: ") if s.startswith("A") or s.startswith("a"): print("Starts with A") else: print("Does not start with A")

Output

 
OUTPUT 1 :
Enter a string: Apple
Starts with A 

OUTPUT 2 :
Enter a string: Orange
Does not start with A 

Python String startswith()

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

Example 2 :

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

Output

 
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 Trueif the string starts with the specified prefix.
  • It returns Falseif the string doesn't start with the specified prefix.

Python String startswith()

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

Example 3 : 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)

Output

 
OUTPUT :
False
True
True

Example 4 : 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)

Output

 
OUTPUT :
True
False
True

Passing Tuple to startswith()

Example 5 : 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)

Output

 
OUTPUT :
True
False
False