簡體   English   中英

如何編寫一個接受字符串並返回該字符串中的第一個單詞的函數

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

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM