字符串连接

作者: 朱兰Juran | 来源:发表于2022-05-09 08:27 被阅读0次

    字符串连接 ( + 号连接)

    可以使用 + 号连接任意两个字符串,连接字符串时,无论是使用单引号还是双引号创建的都可以。

    Python 控制台运行:

    >>> "Spam" + 'eggs'

    'Spameggs'

    >>> print("First string" + ", " + "second string")

    First string, second string


    字符串连接

    即使你的字符串包含数字,它们仍然被添加为字符串而不是整数。将一个字符串加上数字中会产生一个错误,即使它们看起来相似,但它们是两个不同的实体。

    print("2" + "2")

    print(1 + '2' + 3 + '4')

    尝试一下

    结果:

    22

    Traceback (most recent call last):

      File "..\Playground\", line 3, in <module>

        print(1 + '2' + 3 + '4')

    TypeError: unsupported operand type(s) for +: 'int' and 'str'

    在将来的课程中,只会显示最后一行错误消息,因为它是唯一一个提供发生的错误类型的详细信息。


    字符串操作(乘以整数)

    字符串也可以乘以整数。这会产生原始字符串的重复版本。字符串和整数的顺序无关紧要,但字符串通常是放在前面的。

    字符串不能与其他字符串相乘。即使浮点数是整数,字符串也不能乘以浮点数。

    例如:

    print("spam" * 3)

    print(4 * '2')

    print('17' * '87')

    print('pythonisfun' * 7.0)

    尝试一下

    运行结果:

    spamspamspam

    2222

    Traceback (most recent call last):

      File "..\Playground\", line 5, in <module>

        print('17' * '87')

    TypeError: can't multiply sequence by non-int of type 'str'

    相关文章

      网友评论

        本文标题:字符串连接

        本文链接:https://www.haomeiwen.com/subject/hlacurtx.html