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

  • 5
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值