一、字符串的概念
字符串是由字母、符号、数字等组成的一连串字符,一般放在一组单引号或双引号中间。一个字符串的单引号或双引号必须匹配。请看下面的代码示例:
first_name = 'David'
last_name = "Smith"
print(first_name)
# David
print(last_name)
# Smith
如果字符串较长,而且是多行,则可以将该字符串放在一组符号(''',三个单引号)中间。请看下面的代码示例:
print('''
I wandered lonely as a cloud
That floats on high o'er vales and hills,
When all at once I saw a crowd,
A host of golden daffodils;
Beside the lake, beneath the trees,
Fluttering and dancing in the breeze.
Continuous as the stars that shine
And twinkle on the Milky Way,
They stretched in never-ending line
Along the margin of a bay:
Ten thousand saw I at a glance,
Tossing their heads in sprightly dance.
The waves beside them danced, but they
Out-did the sparkling waves in glee:
A poet could not but be gay,
In such a jocund company:
I gazed -and gazed -but little thought
What wealth the show to me had brought:
For oft, when on my couch I lie
In vacant or in pensive mood,
They flash upon that inward eye
Which is the bliss of solitude;
And then my heart with pleasure fills,
And dances with the daffodils.
——(William Wordsworth,1770-1850)
''')
二、字符串的书写方法
1. 字符串内含有引号的书写方法
由于字符串首尾都需要加引号,因此,如果字符串内含有引号,则需要通过下列方法来处理:
(1) 如果字符串内含有单引号,则需要将字符串放在双引号中间。
(2) 如果字符串内含有双引号,则需要将字符串放在单引号中间。
(3)在字符串内的引号前加上转义符\(反斜杠,backslash)。
(4)在字符串引号前加上字母r,r在这里表示raw string,将不转义字符串内任何内容。
请看下面的代码示例:
单双引号转换:
string1 = 'This is the slogan: "Life is short, I use Python!"'
print(string1)