[英]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.