-1

How can I check if a string only contains one word in python.

x = "tell hello"
if "tell" == x
   print(True)
else 
   print(False)

In this case it should print False, because tell isnt the only Word in the string. But tell is always there. There is only the possibility that after tell is no Word following(in which case it should print true) and that an n amount of words is following(in which case it should print false).

1 Answers1

0

Break the string


h = "hello my baby"

# Breaks the string into a list if ' ' are present is seperates them
words = h.split(' ')

then find the word if present in the list

if "baby" in words:
   print("present")


Edit

And Also You shouldn't use the following code


if "hello" in h:
   print("present")

because if h='hellomy baby' still output will be the same as h="hello my baby" and you don't want that

Also for faster performance one may use


words = set(h.split(' '))

  • 1
    Would use a set here for a more efficient lookup: `words = set(h.split(' '))` – flakes Apr 06 '22 at 06:13
  • Yes you can do that but what's the point anyway if a word is present twice it would also output the same result as the list version – ishantiwari Apr 06 '22 at 06:14
  • 2
    yes, same result but less memory and faster anyway (set in python is a hashtable) – CuCaRot Apr 06 '22 at 06:16
  • Its not to reduce duplicates. Its to get an O(1) lookup on `if "baby" in words` vs the O(n) lookup using the list which always has to scan from the beginning of the list, checking each value individually. – flakes Apr 06 '22 at 06:17
  • Oh I get it Now... Should I edit the post to make `words = set(h.split(' ')) – ishantiwari Apr 06 '22 at 06:20
  • This won't work for any realistic text. For instance if `h = "hello, my baby"` you get `"hello" in words==False`. For splitting a text into words one needs some regular expression that also takes punctuation into consideration, this is called "tokenization". – user2314737 Apr 06 '22 at 06:21
  • Then you can have a list of these punctuation marks like `puncs= [',', '.'] ` and also you can split them first using these marks and then join them with '' and then split again with spaces then you may seek your word. One can create a specific algorithm for that – ishantiwari Apr 06 '22 at 06:33