Python:怎样拼装超长字符串和包含回车换行字符串

最近更新时间 2020-11-28 12:58:10

Python 中字符串可以使用单引号('……')或双引号("……")表示。反斜杠 \ 是转义字符。如果你不希望 \ 转义字符成特殊字符,可以在引号前添加 r 即可。如下所示:

"first_name"
# Output: first_name

'\'last_name\''
# Output: 'last_name'


# 没有特殊字符
path = r'd:\some\name'
# Output: d:\some\name

如果字符串很长,包括回车和换行用 ' 或 " 已经不能很好的表示。可以使用三重引号:"""...""" 或 '''...'''。字符串中的回车换行会自动包含到字符串中,如果不想包含,在行尾添加一个 \ 即可。如下所示:

table = """\
CREATE TABLE `employees` (
  `emp_no` int(11) NOT NULL AUTO_INCREMENT,"
  `birth_date` date NOT NULL,"
  `first_name` varchar(14) NOT NULL,"
  `last_name` varchar(16) NOT NULL,"
  `gender` enum('M','F') NOT NULL,"
  `hire_date` date NOT NULL,"
  PRIMARY KEY (`emp_no`)"
) ENGINE=InnoDB
"""
CREATE TABLE `employees` (
  `emp_no` int(11) NOT NULL AUTO_INCREMENT,"
  `birth_date` date NOT NULL,"
  `first_name` varchar(14) NOT NULL,"
  `last_name` varchar(16) NOT NULL,"
  `gender` enum('M','F') NOT NULL,"
  `hire_date` date NOT NULL,"
  PRIMARY KEY (`emp_no`)"
) ENGINE=InnoDB

相邻两个或多个字符串将会自动连接到一起,该特性对很长的字符串拆开显示非常有用。如下所示:

text = (
    "CREATE TABLE `salaries` ("
    "  `emp_no` int(11) NOT NULL,"
    "  `salary` int(11) NOT NULL,"
    "  `from_date` date NOT NULL,"
    "  `to_date` date NOT NULL,"
    "  PRIMARY KEY (`emp_no`,`from_date`), KEY `emp_no` (`emp_no`),"
    "  CONSTRAINT `salaries_ibfk_1` FOREIGN KEY (`emp_no`) "
    "     REFERENCES `employees` (`emp_no`) ON DELETE CASCADE"
    ") ENGINE=InnoDB")
CREATE TABLE `salaries` (  `emp_no` int(11) NOT NULL,  `salary` int(11) NOT NULL,  `from_date` date NOT NULL,  `to_date` date NOT NULL,  PRIMARY KEY (`emp_no`,`from_date`), KEY `emp_no` (`emp_no`),  CONSTRAINT `salaries_ibfk_1` FOREIGN KEY (`emp_no`)      REFERENCES `employees` (`emp_no`) ON DELETE CASCADE) ENGINE=InnoDB

与三重引号相比,合并后的字符串不会有换行回车,对执行拼装执行命令的字符串更有用。

rss_feed