简体   繁体   中英

How can i find words which are greater than given number of length in python?

I am creating a simple String in python.

str ="A quick brown fox jump over the lamp."
length = 3

I want to check all the words in sentence which are greater than the length of 3 . we want to check the string length is greater than 3 to the given String. We have to find all the words (substrings separated by a space) which are greater than the given length 3.

shorter:

s ="A quick brown fox jump over the lamp."
length = 3
print( [ x for x in s.split() if len(x) > length ] )

You can achieve that with regex by searching for a pattern of \w following by curly braces and the number of chars that you would like to find in a given string.

import re

s ="A quick brown fox jump over the lamp."
length = 3
print(re.findall("\w{{{},}}".format(length), s))

OR in python 3.6 and above

print(re.findall(f"\w{{{length},}}", s))

Output

['quick', 'brown', 'fox', 'jump', 'over', 'the', 'lamp']

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM