发布时间:2022-11-11 文章分类:编程知识 投稿人:王小丽 字号: 默认 | | 超大 打印

这一篇文章主要介绍python字符串相关知识。

单引号字符串及对单引号的转义

字符串(String)就是一段文本,几乎在所有的Python程序中都有字符串的身影。

字符串可以用单引号表示,也可以用双引号表示,但是输出一般为单引号:

>>> 'Hello World!'
'Hello World!'
>>>
>>> "Hello World!" 
'Hello World!'
>>>

如果字符串中有单引号,我们就需要用双引号表示字符串;同样如果字符串中有双引号,我们就需要用单引号表示字符串。否则,会报错

>>> "Let's go!"
"Let's go!"
>>>
>>> '"Hello, world!" she said' 
'"Hello, world!" she said'
>>>
>>> 'Let's go!' 
  File "<stdin>", line 1
    'Let's go!'
         ^
SyntaxError: invalid syntax
>>>
>>> ""Hello, world!" she said" 
  File "<stdin>", line 1
    ""Hello, world!" she said"
      ^^^^^
SyntaxError: invalid syntax
>>>

可以通过转义符\的使用表示字符串里面的引号:

>>>
>>> "\"Hello, world!\" she said" 
'"Hello, world!" she said'
>>> 'Let\'s go!'             
"Let's go!"
>>>

字符串拼接

>>>
>>> "Let's say " '"Hello , world!"'
'Let\'s say "Hello , world!"'
>>>
>>> x = "Hello, "
>>> y = "world!"
>>> x y
  File "<stdin>", line 1
    x y
      ^
SyntaxError: invalid syntax
>>>
>>> x + y
'Hello, world!'
>>>

字符串的str和repr

>>>
>>> "Hello, world!"
'Hello, world!'
>>> print("Hello, world!")
Hello, world!
>>>
>>> "Hello, \nworld!"  
'Hello, \nworld!'
>>> print("Hello, \nworld!") 
Hello, 
world!
>>>
>>> print(repr("Hello, \nworld!")) 
'Hello, \nworld!'
>>> print(str("Hello, \nworld!"))  
Hello, 
world!
>>>

长字符串

要表示很长的字符串(跨越多行的字符串),可以使用三引号(而不是普通的引号):

>>>
>>> print('''This is a very long string. It continues here.
...       And it's not over yet. "Hello, world!"
...       Still here.''')
This is a very long string. It continues here.
      And it's not over yet. "Hello, world!"
      Still here.
>>> 
>>> 1 + 2 + \   
... 4 + 5   
12
>>>
>>> print\  
... ('Hello, world!') 
Hello, world!
>>>

原始字符串

原始字符串不以特殊方式处理反斜杠,因此在有些情况下很有用,例如正则表达式中。

因为反斜杠对字符进行转义,可以表达字符串中原本无法包含的字符,但是如果字符中本身就有反斜杠或包含反斜杠的组合,就会出问题。这个时候有两种方案:

例如我们想要表达文件路径:

>>>
>>> print('C:\Program Files\fnord\foo\baz')   
C:\Program Files
                nord
                    oaz
>>>
>>> print('C:\\Program Files\\fnord\\foo\\baz')
C:\Program Files\fnord\foo\baz
>>>
>>> print(r'C:\Program Files\fnord\foo\baz')  
C:\Program Files\fnord\foo\baz
>>>
>>> print(r'Let\'s go!')
Let\'s go!
>>>   
>>> print(r'C:\Program Files\fnord\foo\baz' '\\' ) 
C:\Program Files\fnord\foo\baz\
>>>