虽然循环对我来说是新的,但我无法让我的代码验证。
描述
在本练习中,您的函数将收到两个参数:a string(long_word)和一个字符(char)。使用while循环去 通过字符串中的所有字母并构建一个新的字符串 从那些信件直到你找到了char。你可以假设每一个 string将包含传入的字符(char)。
这是我的代码。
def letters_up_to_char(long_word, char):
new = ""
i = 0
while i != char:
for letter in long_word:
new += letter
i += 1
return new
示例输出
letters_up_to_char('coderoxthesox', 'x') -> 'codero'
letters_up_to_char('abcdefghijklmnop', 'f') -> 'abcde'
当我去运行我的代码时,我得到了:
TypeError: cannot concatenate 'str' and 'int' objects
答案 0 :(得分:1)
要摆脱
TypeError: cannot concatenate 'str' and 'xyz' objects
,只需 将被连接的对象转换为字符串。如果您的代码是string + num
或string += num
只是将num
转换为字符串,如下所示:str(num)
但是,您的代码无法返回所需的输出。请参阅下面的原因:
如果我没有弄错,代码不应该编译,因为定义new
时,您不会关闭双引号即可。或者,如果您使用单引号,请更改代码和问题以反映您的更改。
当我运行你的代码并执行它时,它进入了无限循环,这是初学者最大的敌人!在你的代码中,
for letter in long_word:
new += letter
与说new += long_word
相同,因为您只是一次性添加单个字符而不是整个字符串。
然后可以按如下方式重写您的代码:
def letters_up_to_char(long_word, char):
new = ""
i = 0
while i != char:
new += long_word
i += 1
return new
现在很清楚你的代码在做什么。它只是在每次执行while循环时将整个单词添加到new
。而while循环执行到i != char
。由于i
是int
而char
是str
,因此i != char
始终为真。正在制作无限循环!
您的功能应如下所示:
def letters_up_to_char(long_word, char):
new = ""
i = 0
while i < len(long_word) and long_word[i] != char:
new += long_word[i]
i += 1
return new
说明:
从头开始浏览long_word
中的每个字符(使用for...in
循环可以更轻松地完成此操作,但我可以根据您的请求使用while循环)直到当前字符! = char
,将该字符添加到new
。
此代码返回两个测试用例的所需输出。
答案 1 :(得分:1)
考虑
您可以假设每个字符串都包含传入的内容 字符(CHAR)。
不包括char:
def letters_up_to_char(long_word, char):
i=0
while long_word[i] != char:
i+=1
return long_word[:i]
包括char:
def letters_up_to_char(long_word, char):
i=0
while long_word[i] != char:
i+=1
return long_word[:i+1]
虽然更加pythonic的方式,即:
def letters_up_to_char(long_word, char):
return long_word.partition(char)[0]
建议您在完成作业时使用http://docs.python.org/3/tutorial/index.html作为参考。
答案 2 :(得分:0)
&#34; i&#34;是int
类型,无法与str
类型&#34; char&#34;进行比较。
while i < len(long_word) and long_word[i] != char
答案 3 :(得分:0)
有几种方法可以编写此代码。在您的示例中,while i != char
行将导致非常长的循环,因为它将循环到i == int(char)
,或者可能无限循环。我会用for
或 a while
来编写,如下所示:
def letters_while(long_word, char):
new = ""
i = 0
# A second condition is needed to prevent an infinite loop
# in the case that char is not in long_word
while long_word[i] != char and i < len(long_word):
new += letter
i += 1
return new
def letters_for(long_word, char):
new = ""
for letter in long_word:
if letter != char:
new += letter
return new
请注意,这些是易于理解的示例,更好的方法是
long_word.split(char)[0]