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

本文完。

猜你喜欢

转载自www.cnblogs.com/oddcat/p/9648822.html