Home > Software engineering >  How do I Write a function that takes in a string and returns the first word in that string
How do I Write a function that takes in a string and returns the first word in that string

Time:10-14

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.

CodePudding user response:

def func(string): #eg. "Hello World"
        string_to_list = string.split() #["Hello", "World"]
        first_word = string_to_list[0]  #"Hello"
        
        return first_word

CodePudding user response:

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)
  • Related