要将一个list的字符串连接起来显示,要求如下:
Create a function that concatenates strings.
- Define a function called
join_strings
accepts an argument calledwords
. It will be a list. - Inside the function, create a variable called
result
and set it to""
, an empty string. - Iterate through the
words
list and append each word toresult
. - Finally,
return
theresult
.
Don't add spaces between the joined strings!
被要求的第三条的“append”误导了,写了这么一个程序:n = ["Michael", "Lieberman"]
# Add your function here
def join_strings(words):
result=""
for word in words:
result.append(word)
return result
print join_strings(n)
结果:
Traceback (most recent call last):
File "python", line 11, in <module>
File "python", line 6, in join_strings
AttributeError: 'str' object has no attribute 'append'
百思不得其解,还是百度了一下,说是因为str没有append这个用法,看来自己还是太死脑筋了,最近用append太多导致以为应该会是append,想了一下,直接用符号+就能够将两个字符连接起来显示。
改了一下程序:
n = ["Michael", "Lieberman"]
# Add your function here
def join_strings(words):
result=""
for word in words:
result+=word
return result
print join_strings(n)
结果正常显示:
MichaelLieberman
append是用于list的,比如将两个list的数据连起来:
n = [[1, 2, 3], [4, 5, 6, 7, 8, 9]]
# Add your function here
def flatten(lists):
results=[]
for numbers in lists:
for number in numbers:
results.append(number)
return results
print flatten(n)
结果显示:
[1, 2, 3, 4, 5, 6, 7, 8, 9]
这件事告诫我们不要死学,不知道这是不是CodeCademy的意图。哈哈哈哈