[英]Write a function named first_word that returns the first word in a string
[英]How do I Write a function that takes in a string and returns the first word in that string
所以我有几个短语 X、Y 和 Z 如何创建一个函数来从每个短语中选择第一个单词。 我试过了:
def first(value):
return value[0]
def first(text)
return text.split[1]
我对此完全陌生,我找不到可能对此有用的方法。
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)
这奏效了。 但我会看看你的答案,看看什么有效或我如何使用它。 附带问题:是否有或可以有多种解决方案?
欣赏您的回答!
def first_word(value):
return value.split(' ')[0]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.