Learn python with socratica [My notes] - part 2 - Strings

Lesson 3

Introdiction to Strings

在python中,对字符串的操作有很多,下面用三种方式进行操作:

Method One

直接用双引号编写字符串,然后直接打印出来。

message = "Meet me tonight."
print(message)

Meet me tonight.

Method Two

用单引号编写字符串,让我们试试看

message2 = 'The clock strikes at midnight'
print(message2)

The clock strikes at midnight

Debug

因此我们可以使用双引号和单引号来编写简单的文本,python可以聪明地识别出来。但是为什么会有多种方式去定义字符串呢?这样会有什么样的问题呢?是否这两者可以随意使用?让我们做实验看看:

message3 = 'I'm looking for someone to share in the adventure.'

  File "<ipython-input-5-97e495e723a5>", line 1
    message3 = 'I'm looking for someone to share in the adventure.'
                  ^
SyntaxError: invalid syntax

你可以看到I’m 的单引号与表示字符串的单引号发生了冲突,因此报了语法错误SyntaxError。那么我们应该如何修改这个错误呢?我们有两种方式:

# first method
message3 = 'I\'m looking for someone to share in an adventure.'
print(message3)

I'm looking for someone to share in an adventure.



# second method
message3 = "I'm looking for someone to share in an adventure."
print(message3)

I'm looking for someone to share in an adventure.

同样地,如果文本中有双引号时,也会有类似的错误,让我们实验一下:

# error
message4 = "The phrase "Beam me up, Scotty" was never said on Star Trek."

  File "<ipython-input-9-bd8f6c249536>", line 1
    message4 = "The phrase "Beam me up, Scotty" was never said on Star Trek."
                               ^
SyntaxError: invalid syntax

我们可以看到同样类似的错误,修改方式如下:

# correct
message4 = 'The phrase "Beam me up, Scotty" was never said on Star Trek.'
print(message4)

The phrase "Beam me up, Scotty" was never said on Star Trek.

Method Three

使用三引号编写字符串——在编辑文本时不止有这几种情况,python也考虑到了,在处理嵌套多个引用语的句子中该如何编辑:

# it is needed to type in line by line with terminal
movie-quote = """One of my favorite lines from The Godfather is:
                "I'm going to make him an offer he can't refuse."
                Do you know who said this?"""

Conclusion

因此你可以使用单引号、双引号和三引号来编辑字符串文本,合理地使用三者避免语法错误的产生。

Youtube source:
https://www.youtube.com/watch?v=bY6m6_IIN94&list=PLi01XoE8jYohWFPpC17Z-wWhPOSuh8Er-