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
與三重引號相比,合併後的字符串不會有換行回車,對執行拼裝執行命令的字符串更有用。