Python学习笔记(4),字符串没有append用法

要将一个list的字符串连接起来显示,要求如下:

Create a function that concatenates strings.

  1. Define a function called join_strings accepts an argument calledwords. It will be a list.
  2. Inside the function, create a variable called result and set it to"", an empty string.
  3. Iterate through the words list and append each word toresult.
  4. Finally, return the result.

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的意图。哈哈哈哈

你可能感兴趣的:(python,append,Codecademy)