iT邦幫忙

0

字串處理python

  • 分享至 

  • xImage

將輸入的英文句子依序進行以下幾個步驟的處理,並將每個步驟處理的結果輸出到螢幕上。
將輸入的字串使用空白字元進行字串切割,請找出句子 中所有單字,顯示所有單字出來。
將上一題的結果以空白字元還原回原來的字串。
將輸入的字串的所有單字的字首大寫。

圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

1 個回答

1
mackuo
iT邦研究生 2 級 ‧ 2023-01-07 14:57:49

輸入問題給某知名AI chat,
解答如下:

def process_sentence(sentence):
  # 將輸入的字串使用空白字元進行字串切割,請找出句子中所有單字
  words = sentence.split()
  print("所有單字:", words)

  # 將上一題的結果以空白字元還原回原來的字串
  sentence_restored = " ".join(words)
  print("還原後的字串:", sentence_restored)

  # 將輸入的字串的所有單字的字首大寫
  words_capitalized = [word.capitalize() for word in words]
  print("字首大寫後的單字:", words_capitalized)

# 執行程式
sentence = "this is a test sentence"
process_sentence(sentence)

執行結果:

所有單字: ['this', 'is', 'a', 'test', 'sentence']
還原後的字串: this is a test sentence
字首大寫後的單字: ['This', 'Is', 'A', 'Test', 'Sentence']

akajoke iT邦新手 5 級 ‧ 2023-01-08 16:05:38 檢舉

太屌了XDDD 好帥

我要發表回答

立即登入回答