1.1 字符串是什么

  1. 方式1
'单引号之间的文字'  #注意引号是英文状态下的
  1. 方式2
'双引号其实和单引号的作用是一样的'  #注意引号是英文状态下的
  1. 方式3
'''
三个引号被用于过长的文字或是说明,
只要三个引号不结束,
你就可以一直写下去
'''
#注意引号是英文状态下的

1.2 字符串的基本用法

1.2.1 合并

>>> what_he_does = ' plays '
>>> his_instrument = ' guitar '
>>> his_name = ' hengbin '
>>> artist_intro = his_name + what_he_does + his_instrument
>>> print(artist_intro)
 hengbin  plays  guitar

python中表示英文字符的代码 python字符串的英文_单引号

1.2.2 数据类型转换

  如图,数据类型不同,不能直接进行字符串组合或者数字相加。可以使用type()查看类型

另外,由于中文注释也会导致报错,故编写python时,最好首行加入#coding:utf-8

python中表示英文字符的代码 python字符串的英文_小游戏_02

>>> num = 1
>>> string = '1'
>>> num2 = int(string)
>>> print(num + num2)
2

python中表示英文字符的代码 python字符串的英文_字符串_03

1.2.3 字符串相乘

>>> word = ' word '*3
>>> print(word)
 word  word  word

python中表示英文字符的代码 python字符串的英文_python中表示英文字符的代码_04

>>> word = 'a loooooong word'
>>> num = 12
>>> string = 'bang!'
>>> total = string * (len(word) - num) #total=‘bang’ * (16 - 12)
>>> print(total)
bang!bang!bang!bang!

python中表示英文字符的代码 python字符串的英文_字符串_05

1.3 字符串的分片与索引

  1. 教材实例

python中表示英文字符的代码 python字符串的英文_python中表示英文字符的代码_06


python中表示英文字符的代码 python字符串的英文_单引号_07

  1. 小游戏

1.4 字符串的方法

python中表示英文字符的代码 python字符串的英文_字符串_08


方法:比如汽车是car,其中drive是他的重要功能_称为方法。若我们要使用这各功能(方法),则使用car.drive()

  1. 当注册账户时,为保障用户安全,一般只显示4位,其余使用“*”来代替。

python中表示英文字符的代码 python字符串的英文_python中表示英文字符的代码_09


python中表示英文字符的代码 python字符串的英文_python中表示英文字符的代码_10

>>> phone_number = '1586-843-2477'
>>> hiding_number = phone_number.replace(phone_number[:9],'*'*9)
>>> print(hiding_number)
*********2477

  其中那个,我们使用了一个新的字符串方法replace()进行“遮挡”。replace方法的括号中,第一个phone_number[:9]代表要被替换掉的部分,后面的'*'*9表示将要替换成什么字符。

  1. 联想功能,模糊查询(实际实现要比这个难,此处只为说明原理)
>>> search = '168'
>>> num_a = '1386-168-0006'
>>> num_b = '1681-222-0006'
>>> print(search + ' is at ' + str(num_a.find(search)) + ' to '+str(num_a.find(search) + len(search)) + ' of num_a')
168 is at 5 to 8 of num_a
>>> print(search + ' is at ' + str(num_b.find(search)) + ' to '+str(num_a.find(search) + len(search)) + ' of num_b')
168 is at 0 to 8 of num_b
>>>

python中表示英文字符的代码 python字符串的英文_字符串_11

1.5 字符串格式化符

python中表示英文字符的代码 python字符串的英文_字符串_12


如上图英文题目一样,当字符串中有很多空需要填写的时候,我们可以使用.format()进行批处理,它的使用方法有以下几种。

python中表示英文字符的代码 python字符串的英文_小游戏_13


这种字符串填空的方式使用广泛,例如如下代码可以填充王志忠的空缺的城市数据。

python中表示英文字符的代码 python字符串的英文_单引号_14