Python-How to print specific word in a string.

 How to print specific word in a string.



To print specific word in a string you need to break string into list of words with split() method and then access specific word by index.


How to create list of words.

s = 'This is a string'
s = s.split()
print(s)
Method split() breaks the string into list.
['This', 'is', 'a', 'string']

How to print specific word.

s = 'This is a string'
s = s.split()
print(s)
print(s[0])
 Python start indexing from "0" so to have printed first word you have tell Python you want to print element with index 0.
['This', 'is', 'a', 'string']
This

If you want print second word which is 'is' you want to use index '1'.
s = 'This is a string'
s = s.split()
print(s)
print(s[1])
['This', 'is', 'a', 'string']
is


How to print few specific words in a string.

Let's say you want to to print first two words in a string "This is a string".

s = 'This is a string'
s = s.split()
print(s)
print(s[0:2])
print(s[0:2]) tells Python to print words indexed from 0 to 2. It might get confusing at beginning but easier to remember this way: start:end.
['This', 'is', 'a', 'string']
['This', 'is']

So to print words from second to the last you can do it this way:
s = 'This is a string'
s = s.split()
print(s)
print(s[1:])
['This', 'is', 'a', 'string']
['is', 'a', 'string']
By giving not ending point we're telling Python to print elements to the end.



Comments