简体   繁体   中英

How do I Write a function that takes in a string and returns the first word in that string

So I have several phrases X, Y, and Z How do I create a function that selects the first word from each phrase. I have tried:

def first(value):
   return value[0]

def first(text)
   return text.split[1]

I'm totally new at this and I cant find what may work for this.

def func(string): #eg. "Hello World"
        string_to_list = string.split() #["Hello", "World"]
        first_word = string_to_list[0]  #"Hello"
        
        return first_word
text = "   i am mobassir"
def first(text):
  if (text is None) or (str(text).strip()==""): #if string is empty
    return None
  else:
    return text.split()[0]
get_first = first(text)
print(get_first)

This worked. But i will look at your answers to see what does work or how i can use it. Side question: Are there or can there be multiple solutions?

Appreciate your answer!

def first_word(value):
  return value.split(' ')[0]

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