3. Python3的简单基本类型之字符串str(二)

4.2 字符串入门String

字符串的意思就是“一串字符”,比如“Hello,田心木瓜”是一个字符串。
Python中的字符串用单引号 ’ 或双引号 " 括起来,同时使用反斜杠 \ 转义特殊字符(比如对引号进行转义)。也可以在字符串前面添加一个 r,表示原始字符串。

In [1]: txmg = "It is a \'charcter\'." #转义字符的使用
In [2]: print (txmg)

It is a 'charcter'.

字符串的截取的语法格式如下:

变量[头下标:尾下标]

索引值以 0 为开始值,-1 为从末尾的开始位置。

In [3]: ss = 'ABCDEFGHIJ' #定义一个字符串

In [7]: ss[2]
Out[7]: 'C'

In [8]: ss[0]
Out[8]: 'A'

In [9]: ss[-9]
Out[9]: 'B'

In [10]: ss[1]
Out[10]: 'B'

In [11]: ss[-1]
Out[11]: 'J'

在这里插入图片描述
加号 + 是字符串的连接符, 星号 * 表示复制当前字符串,紧跟的数字为复制的次数。实例如下:

In [13]: print (ss[0:-1]) #第一个到最后,不包含最后一个J
ABCDEFGHI

In [14]: print (ss[1:5])  # 输出从第二个开始到第五个的字符
BCDE

In [15]: print (ss[3:]) #输出从第4个开始到最后
DEFGHIJ

In [16]: print (ss * 3) # 输出字符串3ABCDEFGHIJABCDEFGHIJABCDEFGHIJ

In [17]: print (ss + "hhhhh") # 连接字符串
ABCDEFGHIJhhhhh

小结

  • 反斜杠可以用来转义,使用r可以让反斜杠不发生转义。
  • 字符串可以用+运算符连接在一起,用*运算符重复。
  • Python中的字符串有两种索引方式,从左往右以0开始,从右往左以-1开始。
  • Python中的字符串不能改变。

4.2.1 repr和字符串

Python不允许直接拼接数值和字符串,必须先将数值转换成字符串。
可以使用str()或repr()函数,举例如下:
In [18]: meat = "猪肉很贵啊,价钱是:"

In [19]: price = 88.78

In [20]: print (meat + price)
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-20-78cdd90a9753> in <module>
----> 1 print (meat + price)

TypeError: can only concatenate str (not "float") to str

In [21]: print (meat + str(price))
猪肉很贵啊,价钱是:88.78

In [22]: print (meat + repr(price))
猪肉很贵啊,价钱是:88.78

4.2.2 input和raw_input

input()函数用于向用户生成一个提示,然后获取用户输入的内容,此函数总会将用户输入的内容放入字符串中,因此用户输入任何内容,input()函数总是返回一个字符串。
raw_input()是python 2中的,相当于python 3中的input

In [27]: i = input()
1

In [28]: print (type(i))
<class 'str'>

In [29]: j = input()
2.89

In [30]: print (type(j))
<class 'str'>

In [31]: h = input()
hello

In [32]: print (type(h))
<class 'str'>

4.2.3 长字符串

‘’'三个引号一般用于多行注释,但是也可以将它赋值,如下例子。

In [33]: ls = '''"It is a long long long.
    ...: stroy ,please read it.
    ...: are u ok?"
    ...: '''

In [34]: print (ls)
"It is a long long long.
stroy ,please read it.
are u ok?"

4.2.4 bytes

python3 新增bytes类型,str是以多个字符组成, bytes是以多个字节组成,bytes只负责以字节(二进制格式)序列来记录数据,由于bytes保存原始的字节(二进制格式)数据,因此bytes对象可用于网络上传输数据,也可用于存储各种二进制格式的文件。比如图片,音乐等文件。

如果字符串内容都是ASCII字符,则可直接在字符串之前添加b来构建bytes值。
调用bytes()函数,将字符串按照指定字符集转换成bytes,默认使用UTF-8字符集。
调用字符串本身的encode() 方法将字符串按指定字符集转换成bytes,默认使用UTF-8字符集
在这里插入图片描述

4.2.5 字符串格式化

Python提供了“%”对各种类型的数据进行格式化输出,
在这里插入图片描述

In [35]: number = -29

In [36]: print ('number is %6i' % number)
number is    -29

In [37]: print ('number is %6d' % number)
number is    -29

In [38]: print ('number is %6o' % number)
number is    -35

In [39]: print ('number is %6x' % number)
number is    -1d

In [40]: print ('number is %6X' % number)
number is    -1D

In [41]: print ('number is %6S' % number)

In [42]: print ('number is %6s' % number)
number is    -29

%6 -> 6是指输出最小宽度为6。
转换浮点数的宽度可以用%6.3f,感兴趣可以自己试一下

python中字符串还支持用in运算符判断是否包含某个子串,还有获取字符串的长度,用内置len()函数,还可以用min()和max()函数获取字符串中最小字符和最大字符

In [43]: ah = 'This is has two dogs.'

In [44]: 'two' in ah
Out[44]: True

In [48]: 'nn' in ah
Out[48]: False
In [49]: len(ah)
Out[49]: 21

In [50]: min(ah)
Out[50]: ' '

In [51]: max(ah)
Out[51]: 'w'

4.2.6 Python自带两个帮助函数

dir():列出指定类或模块包含的全部内容(包括函数,方法,类,变量等)
help():查看某个函数或方法的帮助文档

感兴趣的可自行尝试, 比如dir(str)

4.2.7 删除多余空白

字符串还提供了了如下常用的方法来删除空白
strip():删除字符串前后的空白
lstrip():删除字符串前面(左边)的空白
rstrip():删除字符串后面(右边)的空白

注意:因为字符串类型是不可变的,所以上述三个方法是删除空白的副本,并没有真正改变字符串本身

In [55]: abc = " the is hh   "

In [56]: print (abc)
 the is hh

In [57]: abc.strip()
Out[57]: 'the is hh'

In [58]: abc.lstrip()
Out[58]: 'the is hh   '

In [59]: abc.rstrip()
Out[59]: ' the is hh'

In [60]: print (abc)
 the is hh

还可以删除指定字符的

In [80]: s123 = 'the is hhhhhhioo'

In [81]: print (s123)
the is hhhhhhioo

In [82]: print (s123.lstrip('th'))
e is hhhhhhioo

In [83]: print (s123.rstrip('isioo'))
the is hhhhhh

In [84]: print (s123.strip('tioo'))
he is hhhhhh

4.2.8 字符串的查找,替换

startswith(): 判断字符串是否以指定子串开头。
endstwith():判断字符串是否以指定子串结尾。
find():查找指定子串在字符串中出现的位置,如果没有知道指定子串,则返回-1.
index():查找指定子串在字符串中出现的位置,如果没有知道指定子串,则引发VauleError错误
replace():使用指定子串替换字符串中的目标子串。
translate():使用指定的翻译映射表对字符串执行替换。

感兴趣自行测试即可,不在这里演示了哈。

4.2.9 字符串的分割,连接方法

split(): 将字符串按指定分隔符分割成多个短语
join(): 将多个短语连接成字符串

In [87]: print (a1.split()) #使用空白对字符串进行分割
['crazyPython', 'is', 'a', 'good', 'book']

In [88]: print (a1.split(None, 2)) #使用空白对字符串进行分割,最多只分割前两个单词
['crazyPython', 'is', 'a good book']

In [91]: print (a1.split('y')) #使用y来进行分割
['craz', 'P', 'thon is a good book']

In [92]: my_a1 = a1.split()
In [94]: print (my_a1)
['crazyPython', 'is', 'a', 'good', 'book']

In [95]: print ('/'.join(my_a1))
crazyPython/is/a/good/book

In [96]: print (','.join(my_a1))
crazyPython,is,a,good,book

4.2.9 运算符

python运算符:

  • 赋值运算符

在这里插入图片描述

  • 算术运算符
  • 位运算符
  • 索引运算符
In [97]: a10 = 'abcdefghijklmnopq'
In [99]: print (a10[2:8:3]) #获取索引2到索引8的子串,步长为3
cf

In [100]: print (a10[2:8:2]) #获取索引2到索引8的子串,步长为2
ceg

  • 比较运算符
    在这里插入图片描述
    在这里插入图片描述
  • 逻辑运算符

三目运算符

In [101]: bb = 12

In [102]: cc = 4

In [103]: st = "bb 大于 cc" if bb > cc else "bb不大于cc"

In [104]: print (st)
bb 大于 cc

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值