Skip to content Skip to sidebar Skip to footer

Retrieve First Word In List Index Python

I want to know how to retrieve the first word at list index. For example, if the list is: ['hello world', 'how are you'] Is there a way to get x = 'hello how'? Here is what I've t

Solution 1:

A simple generator expression would do, I guess, e.g.

>>>l = ["hello world", "how are you"]>>>' '.join(x.split()[0] for x in l)
'hello how'

Solution 2:

You're not far off. Here is how I would do it.

# Python 3
newfriend = ['hello world', 'how are you']
x = []  # Create x as an empty list, rather than an empty string.for v in newfriend:
    x.append(v.split(' ')[0])  # Append first word of each phrase to the list.

y = ' '.join(x)  # Join the list.print(y)

Solution 3:

import re
#where l =["Hello world","hi world"]
g=[]
for i inrange(l):
   x=re.findall(r'\w+',l[i])
   g.append(x)
print(g[0][0]+g[1][0])

Post a Comment for "Retrieve First Word In List Index Python"