简体   繁体   English

如何编写一个接受字符串并返回该字符串中的第一个单词的函数

[英]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.所以我有几个短语 X、Y 和 Z 如何创建一个函数来从每个短语中选择第一个单词。 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]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 编写一个名为 first_word 的 function 返回字符串中的第一个单词 - Write a function named first_word that returns the first word in a string 您如何在Python中编写一个函数,该函数需要一个字符串并返回一个新字符串,该字符串是原始字符串,并且重复了所有字符? - How do you write a function in Python that takes a string and returns a new string that is the original string with all of the characters repeated? 我如何在 python 中编写一个 function 作为输入 2 个数字和 1 个字符串 - How do I write a function in python that takes as input 2 numbers, and 1 string 如何编写一个函数 function(n) 接受一个整数,并使用 while 循环返回前 n 个偶数的总和? - How do I write a function function(n) that takes in an integer, and returns the sum of the first n even numbers using a while loop? 如何编写接收字符串消息并返回带有分页的字符串消息列表的函数 - How to write function that takes in a string message and returns a list of string messages with pagination Stemmer function 接受一个字符串并返回列表中每个单词的词干 - Stemmer function that takes a string and returns the stems of each word in a list 我想编写一个函数,该函数接受一个列表并返回所有已删除的重复项,而不创建另一个列表或字符串 - I want to write a function that takes a list and returns it with all duplicates removed, without creating another list or string python 基础知识 - 我正在尝试编写一个 function,它将一个字符串(一个月)作为输入并返回该月的天数 - python basics - I am trying to write a function which takes a string(a month) as an input and returns the amount of days in the month 编写一个 function 打印字符串中第一个空格后的第一个单词 - Write a function that prints the first word after the first space in a string 写一个 function 需要 2 个字符串 arguments - write a function that takes 2 string arguments
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM