2.Python语法——字符串

1.字符串的创建

可以使用单引号、双引号、三引号创建,其中三引号创建可以换行的字符串。

a='hello'
b="hello"
c='''hello
     world'''#可以换行

2.字符串的驻留机制

定义:相同值的字符串在字符串池中只保留一个对象

优点:当需要值相同的字符串时,可以直接从字符串池中拿来使用,避免频繁的创建和销毁,提升效率和节约内存

缺点:创建驻留机制的字符串要花费更多的时间

驻留机制的几种情况(交互模式下使用,PaCharm中有字符串优化,实现不了驻留机制):

1.字符串的长度是0或者1

>>> a=''
>>> b=''
>>> id(a)==id(b)
True
>>> m='a'
>>> n='a'
>>> id(m)==id(n)
True
>>> y='%'
>>> s='%'
>>> id(y)==id(s)
True
>>>

2.字符串只包含数字、字母、下划线

>>> s1='ab2_'
>>> s2='ab2_'
>>> id(s1)==id(s2)
True
>>> s3='ab2_%'
>>> s4='ab2_%'
>>> id(s3)==id(s4)
False
>>>

3.字符串只有编译时驻留,而非运行时

>>> s5='abc'
>>> s6='a'+'bc'
>>> id(s5)==id(s6)
True
>>> s7='a'
>>> s8=s7+'bc'
>>> id(s5)==id(s8)
False
>>>

4.[-5,256]之间的数字

>>> a=-5
>>> b=-5
>>> id(a)==id(b)
True
>>> a=-6
>>> b=-6
>>> id(a)==id(b)
False
>>>

强制驻留机制的实现:s1=sys.intern(s2)

3.字符串的操作

1.字符串操作符

        连接符:+

        复制符:*

        判断符:in/not in

print('a'+'bc')
print('a'*40)
print('h' in 'hello')
print('h' not in 'hello')

#结果:
abc
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
True
False

 2.字符串处理函数(内置函数,直接使用)

len()——求字符串长度

str()——将任意数据类型转成字符串类型

chr()——将Unicod码转成字符

ord()——将字符转成Unicode码

bin()、oct()、hex()——将十进制转成二进制、八进制、十六进制,转换结果是字符串类型

3.字符串处理方法(字符串加.调用)

str.lower()——全部字符转小写

str.upper()——全部字符转大写

A='ABC'
a=A.lower()
print(a)
print(a.upper())

#结果:
abc
ABC

str.split(sep=None)——字符串劈分,默认以空格分,也可以自己指定,结果是一个列表

print('a b c'.split())
print('a-b-c'.split('-'))
print('a b c'.split(sep=None))
print('a-b-c'.split(sep='-'))

#结果:
['a', 'b', 'c']
['a', 'b', 'c']
['a', 'b', 'c']
['a', 'b', 'c']

str.count(sub)——统计个数

print('helloword'.count('o'))

#结果:

2

str.replace(old,new)——字符串替换

phone='13836452563'
print(phone.replace(phone[3:7],'****'))

#结果:

138****2563

str.strip(chars)——去掉字符串首尾指定子串

print('hellowordeh'.strip('he'))
#结果:lloword 去掉字符串首尾的指定字符,且与顺序无关
print('hellowordeh'.strip('lo'))
#结果:hellowordeh 指定字符在字符串中间,没法去掉

str.join(iter)——字符串拼接

s='hello'
print(s.join('-'))
#结果:-  join里面必须是一个可迭代对象
print(s.join(['-','-','-']))
#结果:-hello-hello- hello当作用来连接join里面可迭代对象的各个元素,结果是一个字符串类型
print(s.join(('-','-','-')))
#结果:-hello-hello- 
print(s.join({'-','-','-'}))
#结果:-
# join里面可以是元组、列表、字符串

 4.字符串的编码和解码

编码:使用字符串对象的encode()方法,将字符串转成相应编码的字节形式 str-->bytes

解码:使用bytes对象的decode()方法,将字节形式解码为字符串 bytes-->str

#编码
a='字符串'
print(a.encode(encoding='gbk'))
#结果:b'\xd7\xd6\xb7\xfb\xb4\xae'  gbk一个中文占两个字节
print(a.encode(encoding='utf-8'))
#结果:b'\xe5\xad\x97\xe7\xac\xa6\xe4\xb8\xb2' utf-8一个中文占三个字节

#解码
b1=a.encode(encoding='gbk')
b2=a.encode(encoding='utf-8')
print(b1.decode(encoding='gbk'))
#结果:字符串
print(b2.decode(encoding='utf-8'))
#结果:字符串

 5.格式化字符串

name='abc'
age=18
# 使用%
print('我叫%s今年%d' % (name,age))
# 使用字符串对象的format方法
print('我叫{0}今年{1}'.format(name,age))
# 使用f-string
print(f'我叫{name}今年{age}')

#特殊使用
print('{:^20}'.format(name)) #居中对齐
print('{:>20}'.format(name)) #右对齐
print('{:<20}'.format(name)) #左对齐

#结果:

我叫abc今年18
我叫abc今年18
我叫abc今年18
        abc         
                 abc
abc   

你可能感兴趣的:(Python,python,字符串)