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-

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

IndexFziQ

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值