鱼C论坛

 找回密码
 立即注册
查看: 2468|回复: 2

[已解决]为什么这个split()还是没有起作用呢

[复制链接]
发表于 2023-6-12 23:07:58 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
  1. def break_words(sentence):
  2.     """This function will break up words for us."""
  3.     words=stuff.split('sentence')
  4.     return words

  5. sentence="all good things come to those who wait."
  6. words=break_words(sentence)
  7. words
复制代码

截图未命名.jpg
最佳答案
2023-6-12 23:12:41
你的  split()  函数中的参数应该是你想在哪里分割字符串,而不是你想分割的字符串。在你的代码中,你写的  split('sentence')  是告诉Python在'sentence'这个词出现的地方分割字符串,而你的字符串并没有包含'sentence'这个词,所以它没有被分割。

另外一个问题是你的函数  break_words()  中使用的变量是  stuff ,但这个变量在函数内部并没有被定义,应该使用的是函数的参数  sentence 。

所以,你的函数应该改写成下面这样:

  1. def break_words(sentence):
  2.     """This function will break up words for us."""
  3.     words=sentence.split()  # 默认使用空格分割字符串
  4.     return words

  5. sentence="all good things come to those who wait."
  6. words=break_words(sentence)
  7. print(words)
复制代码

这样,你的字符串就会按空格被分割成一个个单词,然后作为一个列表返回。
小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

发表于 2023-6-12 23:12:41 | 显示全部楼层    本楼为最佳答案   
你的  split()  函数中的参数应该是你想在哪里分割字符串,而不是你想分割的字符串。在你的代码中,你写的  split('sentence')  是告诉Python在'sentence'这个词出现的地方分割字符串,而你的字符串并没有包含'sentence'这个词,所以它没有被分割。

另外一个问题是你的函数  break_words()  中使用的变量是  stuff ,但这个变量在函数内部并没有被定义,应该使用的是函数的参数  sentence 。

所以,你的函数应该改写成下面这样:

  1. def break_words(sentence):
  2.     """This function will break up words for us."""
  3.     words=sentence.split()  # 默认使用空格分割字符串
  4.     return words

  5. sentence="all good things come to those who wait."
  6. words=break_words(sentence)
  7. print(words)
复制代码

这样,你的字符串就会按空格被分割成一个个单词,然后作为一个列表返回。
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2023-6-12 23:15:30 | 显示全部楼层
你用sentence切割当然切割不了
还有我想知道你哪来的stuff
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2025-4-24 01:33

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表