zoukankan      html  css  js  c++  java
  • Python——拼接字符串

    Python中可以对字符串进行拼接:

    1. 使用字符串拼接运算符: + 

    >>> "Hello" + "World"
    'HelloWorld'

    或:

    >>> str1 = "Hello"
    >>> str2 = "World"
    >>> str1 + str2
    'HelloWorld'

    又或:

    >>> str1 + "World"
    'HelloWorld'

    但是不允许str类型和整数类型的拼接,否则会报语法错:

    >>> "Hello" + 2018
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    TypeError: must be str, not int

    示例:

    2. 字符串字面量常量同行并呈,Python解释器会将其合并为一个字面量常量:

    字面量常量间无空格:

    >>> "Hello""World"
    'HelloWorld'

    有空格:

    >>> "Hello" "World"
    'HelloWorld'

    并且不限于两个字面量,甚至是多个:

    >>> "Hello " "World, " "Python Newbies"
    'Hello World, Python Newbies'

    但是这种特性仅允许字符串的字面量常量之间,不允许出现字符串变量,如:

    >>> st1 = "Hello"
    >>> str2 = "World"
    >>> str1 str2
      File "<stdin>", line 1
        str1 str2
                ^
    SyntaxError: invalid syntax

    甚至是其中一个是变量,另一个是常量:

    >>> str1 = "Hello"
    >>> str1 "World"
      File "<stdin>", line 1
        str1 "World"
                   ^
    SyntaxError: invalid syntax
    >>> str1"World"
      File "<stdin>", line 1
        str1"World"
                  ^
    SyntaxError: invalid syntax

    本文完。

  • 相关阅读:
    web--ajax--json
    4.26
    4.25
    4.23
    4.22
    4.20
    4.19
    4.18
    4月问题总结章
    4.17
  • 原文地址:https://www.cnblogs.com/oddcat/p/9648822.html
Copyright © 2011-2022 走看看