python基础数据类型——字符串类型及其相关函数

字符串

定义后不可变

字符串可以用' '或者" "括起来表示

字符串的编码用Unicode,可以表示任何书面语言的字符

ASCII是Unicode编码的子集

字符与Unicode码的转换 ord() chr()函数

>>> chr(20989)
'函'
>>> ord('数')
25968

可变字符串

字符串属于不可变对象,不支持原地修改,若修改,需创建新的字符串对象

原地修改需要使用io.StringIO对象或array模块

'hello,world'
>>> ios.seek(7)
7
>>> ios.write('b')
1
>>> ios.getvalue()
'hello,wbrld'

如果字符串既包含'又包含"

Python字符串用\进行转义。

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

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

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

常用的转义字符还有:

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

print('special string:\',\",\\,\\\\,\\n,\\t')

运行结果:

special string:',",,\,\n,\t

raw字符串与多行字符串

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

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

但是r'...'表示法不能表示多行字符串,也r'...'不能表示包含'的字符串。r"..."不能表示包含"的字符串。例如:

这样会发生错误:

>>> print(r'jihd'ji'ko')
  File "<stdin>", line 1
    print(r'jihd'ji'ko')
          ^^^^^^^^^
SyntaxError: invalid syntax. Perhaps you forgot a comma?

这样不会发生错误:

>>> print(r'jihd"ji"ko')
jihd"ji"ko
>>> print(r"jihd'ji'ko")
jihd'ji'ko

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

'''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!'''

字符串内容控制

字符串拼接

>>> a='I\'m '
>>> b='Tom'
>>> print(a+b)
I'm Tom

字符串复制

>>> a='test'
>>> print(a*3)
testtesttest

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.
>>> str='hell{0},w{0}rld'
>>> str.format('o')
'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.

填充与对齐

填充通常与对其一起使用

^,<,>分别是居中,左对齐,右对齐,后面带宽度

:后加填充的字符,只能有一个,不指定默认为空格

>>> "{:*^9}".format('123')
'***123***'
>>> a=123
>>> "{:*^9}".format(a)
'***123***'
>>> b=1
>>> "{:*<9}".format(b)
'1********'

Python的字符串切片slice

可以使用位置的方式取出字符串中特定位置的字符,按照位置取字符串的方式使用中括号[]访问,这个时候可以把字符串看作是一个列表,不过需要注意的是,在程序的世界中,计数是从0开始的,使用0来表示第一个。

[:]	#提取整个字符串

[start:] #从start索引开始到结尾

[:end] #从头开始直到end-1

[start:end] #从start到end-1

[start:end:step]

[::-1]步长为负,从右到左反向提取

例:

>>> str = 'ABCDEFGHIJK'
>>> str[:]
'ABCDEFGHIJK'
>>> str[3:]
'DEFGHIJK'
>>> str[:3]
'ABC'
>>> str[2:5]
'CDE'
>>> str[1:9:2]
'BDFH'
>>> str[::-1]
'KJIHGFEDCBA'

判断字符串长度

方法1:len函数

方法2:for循环

方法3:while循环 切片

方法4:使用字符串join方法和count方法

>>> str = 'ABCDEFGHIJK'
>>> len(str)
11
>>> length = 0
>>> for ch in str :
...     length +=1
...
>>> length
11

成员操作符

in/not in关键字

判断某个字符/字符串是否存在于字符串中

>>> str='aliez'
>>> 'lie' in str
True
>>> 'r' not in str
True

字符串常用函数

>>> str='this is a sentence.'

len()字符串长度

>>> len(str)
19
去除首尾指定信息

strip()

lstrip()去除字符左边指定信息

rstrip()去除右边指定信息

>>> str='*asdfg*'
>>> str.strip('*')
'asdfg'
>>> str.lstrip('*')
'asdfg*'
>>> str.rstrip('*')
'*asdfg'
大小写转换
>>> a = 'hello,WorlD.'

产生新的字符串

a.capitalize()句中仅首字母大写

>>> a.capitalize()
'Hello,world.'

a.title()仅每个单词首字母大写

>>> a.title()
'Hello,World.'

a.upper()所有字母大写

>>> a.upper()
'HELLO,WORLD.'

a.lower()所有字母小写

>>> a.lower()
'hello,world.'

a.swapcase()所有字母大小写转换

>>> a.swapcase()
'HELLO,wORLd.'
格式排版

center()居中填充

ljust(),rjust()

>>> a='hello'
>>> a.center(10,'*')
'**hello***'
>>> a.ljust(10,'*')
'hello*****'
>>> a.rjust(10,'*')
'*****hello'
判断字符串内容

a.startwith() 以指定字符开头

>>> str.startswith('this')
True

a.endwith() 以指定字符结尾

>>> str.endswith('word')
False

a.find() 第一次出现指定字符的位置

>>> str.find('s')
3

a.rfind() 最后一次出现指定字符的位置

>>> str.rfind('s')
10

a.count() 指定字符出现的次数

>>> str.count('s')
3

a.isalnum() 是否所有字符全是字符或数字

>>> a = 'asd123'
>>> a.isalnum()
True
>>> str='this is a sentence.'
>>> str.isalnum()
False

a.isalpha() 是否只有字符或汉字组成

>>> a = '你好asd'
>>> a.isalpha()
True
>>> a = '你好,asd'
>>> a.isalpha()
False

a.isdigit()是否只有数字组成

>>> a = '123'
>>> a.isdigit()
True
>>> a = '123.'
>>> a.isdigit()
False

a.isspace()是否为空白符

>>> a = ' '
>>> a.isspace()
True
>>> a =''
>>> a.isspace()
False
>>> a='\n'
>>> a.isspace()
True

a.isupper()是否为大写字母

>>> a = 'hello,WorlD.'
>>> a.isupper()
False
>>> a = 'ASD123'
>>> a.isupper()
True

a.islower()是否为小写字母

>>> a = 'hello,WorlD.'
>>> a.islower()
False
>>> a = 'asd123'
>>> a.islower()

字符串驻留机制

仅保存一份相同且不可变字符串的方法,不同的值被存放在字符串驻留池中

python支持字符串驻留机制,对于符合表示规则的字符串(仅包含下划线(_),字母和数字)会启用字符驻留机制

>>> str1='aaa_bb'
>>> str2='aaa_bb'
>>> str1 is str2
True
>>> a='aa#bb'
>>> b='aa#bb'
>>> a is b
False

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值