Jessie.Y's Den

A blog for recoding life in pieces

Arvin.W, another owner.


WELCOME TO OUR WORLD

Multi-Line Strings in Python

​ 在Python中,如何来定义一个多行的字符串呢?下面将介绍三种方法,以及他们的优缺点,最后会给出我自己的建议。

连接(Concatenation)

最容易联想到的就是连接字符串,如下:

str1 = "This is the first line" + \
       "The second line" + \
       "end line"

点评:这种方法非常难看,很不美观。稍微改良的一种方式就是去掉”+”,就像下面这样:

str1 = "This is the first line" \
       "The second line" \
       "end line"

多行语法(Multi-Line String Syntax)

python提供了一种built-in的方式定义多行字符串,如下:

template = """This is first part of the line.
 The second line.
 The end line."""

点评:这种方式比concatenation好多了,但是还是有一些瑕疵,从第二行开始,不能有缩进,不然缩进的部分会被当做字符串中的空格处理,就像这样:

>>> template = """This is the first line.
                  This is the second line.
                  This is the third line."""
>>> print(template)
This is the first line.
              This is the second line.
              This is the third line.

元组语法(Tuple Syntax)

先来例子直观感受下:

>>>template = ("This is the first line."
             "This is the second line."
             "This is the end line.")
>>> print template
This is the first line.This is the second line.This is the end line.

点评:优雅,干净,不易出错。

小评:如果在定义一个超长字符串是,一行写不下,需要另起一行,不妨使用下python的元组语法:简单好用。

最近的文章

umount异步机制

场景介绍 远程map一个块设备到机器上,并将这个设备挂在到某个挂载点,作为runc的rootfs使用 块设备上的文件系统为xfs 删除runc容器过程中,首先umount 挂载点,然后unmap这个块设备,这两个过程中在代码逻辑上是‘严格’顺序执行问题描述在umount文件系统的过程中,会大概率导致umount进程D住(处于Uninterruptible状态中),在dmesg看到的直接原因是:设备umap先于文件系统umount操作执行。但是在代码上,两个操作都是同步调用,即直到um...…

继续阅读
更早的文章

linux环境变量---查看和设置

1、查看linux环境变量 env 查看当前用户的所有环境变量; 查看单个环境变量值;如echo $PATH2、常用的环境变量 PATH:在shell中输入的所有命令都会在该目录查找命令路径;该变量在我们日常环境变量设置中相当常用; LD_LIBRARY_PATH:c程序相关的动态引用库路径;一般在程序运行过程中,需要调用c相关的库时,会到该路径下查到对应库;  LIB:c程序相关的静态库路径;在安装或编译程序时,往往到该路径下查找链接库。3、环境变量设置1)用户可以用过编辑~/...…

继续阅读