Python: Find whether a given string starts with a given character using Lambda
Python Lambda: Exercise-7 with Solution
Write a Python program to find whether a given string starts with a given character using Lambda.
Sample Solution:
Python Code :
# Define a lambda function 'starts_with' that checks if a given string starts with 'P'
starts_with = lambda x: True if x.startswith('P') else False
# Check if the string 'Python' starts with 'P' using the 'starts_with' lambda function
# Print the result which will be 'True' if the string starts with 'P', otherwise 'False'
print(starts_with('Python'))
# Redefine the lambda function 'starts_with' (same as before) to check if a string starts with 'P'
# Check if the string 'Java' starts with 'P' using the 'starts_with' lambda function
# Print the result which will be 'True' if the string starts with 'P', otherwise 'False'
print(starts_with('Java'))
Sample Output:
True False
Explanation:
In the exercise above -
- Defines a lambda function named 'starts_with' that checks if a given string starts with the letter 'P'. The lambda function uses the "startswith()" method, which returns 'True' if the string starts with the specified prefix ('P' in this case), otherwise it returns 'False'.
- Calls the "starts_with()" lambda function with the string 'Python' as an argument:
- The lambda function checks if the string 'Python' starts with 'P'.
- Prints the result of this check, which will be 'True' since the string 'Python' starts with 'P'.
- Redefines the lambda function "starts_with()" (although it's the same as before) and uses it to check if the string 'Java' starts with 'P':
- The lambda function checks if the string 'Java' starts with 'P'.
- Prints the result of this check, which will be 'False' since the string 'Java' does not start with 'P'.
Python Code Editor:
Have another way to solve this solution? Contribute your code (and comments) through Disqus.
Previous: Write a Python program to square and cube every number in a given list of integers using Lambda.
Next: Write a Python program to extract year, month, date and time using Lambda.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://198.211.115.131/python-exercises/lambda/python-lambda-exercise-7.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics