码迷,mamicode.com
首页 > 编程语言 > 详细

Python——拼接字符串

时间:2018-09-14 21:39:23      阅读:139      评论:0      收藏:0      [点我收藏+]

标签:syntax   .com   技术分享   com   error:   info   运算   语法   col   

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

 

本文完。

Python——拼接字符串

标签:syntax   .com   技术分享   com   error:   info   运算   语法   col   

原文地址:https://www.cnblogs.com/oddcat/p/9648822.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!