w3resource

Python: Match if two words from a list of words starting with letter 'P'


26. Words Starting with P

Write a Python program to match if two words from a list of words start with the letter 'P'.

Sample Solution:

Python Code:

import re

# Sample strings.
words = ["Python PHP", "Java JavaScript", "c c++"]

for w in words:
        m = re.match("(P\w+)\W(P\w+)", w)
        # Check for success
        if m:
            print(m.groups())
			

Sample Output:

('Python', 'PHP')

Pictorial Presentation:

Python: Regular Expression -  Match if two words from a list of words starting with letter 'P'.

Flowchart:

Flowchart: Regular Expression - Match if two words from a list of words starting with letter 'P'<.

For more Practice: Solve these Related Problems:

  • Write a Python program to match and print all words from a list that start with the letter 'P'.
  • Write a Python script to filter a list of words, returning only those that begin with 'P' (case-insensitive).
  • Write a Python program to extract and count words starting with 'P' from a given text.
  • Write a Python program to check if at least two words in a list start with 'P' and then return a boolean result.

Python Code Editor:

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

Previous: Write a Python program to convert a date of yyyy-mm-dd format to dd-mm-yyyy format.
Next: Write a Python program to separate and print the numbers of a given string.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.