【Python入门】第三章: Python变量和数据类型三

3. Python变量和数据类型三

3.5 Python的字符串

前面我们讲解了什么是字符串。字符串可以用’ '或者" "括起来表示

如果字符串本身包含’怎么办?比如我们要表示字符串 I’m OK ,这时,可以用" "括起来表示:

"I'm OK"

类似的,如果字符串包含",我们就可以用’ '括起来表示:

'Learn "Python" in imooc'

但是,如果字符串既包含’又包含"怎么办?
这个时候,就需要对字符串中的某些特殊字符进行“转义”,Python字符串用\进行转义

要表示字符串Bob said “I’m OK”
由于’和"会引起歧义,因此,我们在它前面插入一个\表示这是一个普通字符,不代表字符串的起始,因此,这个字符串又可以表示为

'Bob said \"I\'m OK\".'

注意:转义字符 \不计入字符串的内容中

常用的转义字符还有:

\n表示换行
\t 表示一个制表符
\表示 \ 字符本身

示例
请在Python中输出以下字符串special string: ', ", , \, \n, \t

# Enter a code
print("special string: ', \", \\, \\\\, \\n, \\t")

在这里插入图片描述

3.6 Python中raw字符串与多行字符串

如果一个字符串包含很多需要转义的字符,对每一个字符都进行转义会很麻烦。为了避免这种情况,我们可以在字符串前面加个前缀r,表示这是一个 raw 字符串,里面的字符就不需要转义了。例如:

r'\(~_~)/ \(~_~)/'

但是r’…'表示法不能表示多行字符串,也不能表示包含’和 "的字符串。

如果要表示多行字符串,可以用’‘’…‘’'表示:

'''Line 1
Line 2
Line 3'''

上面这个字符串的表示方法和下面的是完全一样的:

'Line 1\nLine 2\nLine 3'

还可以在多行字符串前面添加r,把这个多行字符串也变成一个raw字符串:

r'''Python is created by "Guido".
It is free and easy to learn.
Let's start learn Python in imooc!'''

示例

请把下面的字符串用r’‘’…‘’'的形式改写,并用print打印出来:

'\"To be, or not to be\": that is the question.\nWhether it\'s nobler in the mind to suffer.'
# Enter a code
print(r'''
'\"To be, or not to be\": that is the question.
Whether it\'s nobler in the mind to suffer.'
''')

在这里插入图片描述

3.7 Python的字符串format

字符串是Python程序重要的数据类型,有时候通过字符串输出的内容不是固定的,这个时候需要使用format来处理字符串,输出不固定的内容。
字符串format由两个部分组成,字符串模板和模板数据内容组成,通过大括号{},就可以把模板数据内容嵌到字符串模板对应的位置。

  • 字符串模板
template = 'Hello {}'
  • 模板数据内容
world = 'World'
result = template.format(world)
print(result) # ==> Hello World

如果模板中{}比较多,则容易错乱,那么在format的时候也可以指定模板数据内容的顺序。

  • 指定顺序
template = 'Hello {0}, Hello {1}, Hello {2}, Hello {3}.'
result = template.format('World', 'China', 'Beijing', 'imooc')
print(result) # ==> Hello World, Hello China, Hello Beijing, Hello imooc.
  • 调整顺序
template = 'Hello {3}, Hello {2}, Hello {1}, Hello {0}.'
result = template.format('World', 'China', 'Beijing', 'imooc')
print(result) # ==> Hello imooc, Hello Beijing, Hello China, Hello World.
除了使用顺序,还可以指定对应的名字,使得在format过程更加清晰。
  • 指定{}的名字w,c,b,i
template = 'Hello {w}, Hello {c}, Hello {b}, Hello {i}.'
world = 'World'
china = 'China'
beijing = 'Beijing'
imooc = 'imooc'
  • 指定名字对应的模板数据内容
result = template.format(w = world, c = china, b = beijing, i = imooc)
print(result) # ==> Hello World, Hello China, Hello Beijing, Hello imooc.

示例

请使用两种format的方式打印字符串Life is short, you need Python。

# Enter a code
tem1 = 'Hello {}'
tem2 = 'Hello {0} {1}'
tem3 = 'Hello {w}'

print(tem1.format('Python'),tem2.format('My','Python'),tem3.format(w = 'Python'))

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/weixin_42473228/article/details/125582907