python字符串的基本操作

python3中字符串是由unicode码点组成的不可变序列

以下是一些基本的操作:

#format()拼接方式
s1="{} is a {}.".format('wangcai','dog')
print(s1)
s3='{name1} is a {name2}.'.format(name2='dog',name1='wangcai')
print(s3)
'''
wangcai is a dog.
wangcai is a dog.
'''

tuple1=('hello','','world')
tuple_like=('hello' ' ' 'world')
print(type(tuple1))
print(type(tuple_like))
print(tuple_like)
print(tuple1)
'''
<class 'tuple'>
<class 'str'>
hello world
('hello', '', 'world')
'''

#常用的字符串连接'+'
str1='hello'
str2='world'
print(str1+' '+str2)
'''
hello world
'''
#字符串是不可变类型,新生成一个字符串会占用一个新的内存空间

#join拼接方式,
str1_list=['i','am','a','student']
str1_join=' '.join(str1_list)
print(str1_join)
'''
i am a student
'''
#split方法split('分隔符',maxsplit=)
s='zhang haoyun is a student'
print(s.split())
print(s.split(maxsplit=3))
#strip()方法,去除字符串   前后的    空格或者给定的字符,一定是字符串前或后
s1='***       *    **helloworld***        '
print(s1.strip('*'))#       *    **helloworld***
#字符串的查找find()和index(),主要区别是find()不会报错,返回-1,而index()会报错。
print(s.find('h'))
print(s.index('b'))
'''
Traceback (most recent call last):
  File "E:/python/character.py", line 10, in <module>
    print(s.index('b'))
ValueError: substring not found
['zhang', 'haoyun', 'is', 'a', 'student']
['zhang', 'haoyun', 'is', 'a student']
       *    **helloworld***        
1
'''

 

#具有不可变类型的所有操作:
s1='hello world'
s2='hello'
print('h' in s1)
print(s2 not in s1)
print(s2*5)
print(len(s1))
print(s1.count('o'))
print(s1.index('r'))
'''
True
False
hellohellohellohellohello
11
2
8
'''

 这一部分是写Python3字符编码的。

#字符转unicode编码
#python3中字符串开头的u被省略,而b不能被省略
print(ord('中'))
#ord用来返回unicode编码的数值
print(chr(20013))
#chr正好相反。
print(hex(ord('中')))
print(hex(ord('A')))
'''
0x4e2d
0x41
'''
print('中国'.encode('utf8'))#b'\xe4\xb8\xad\xe5\x9b\xbd'这是字节码。
print(b'\xe4\xb8\xad\xe5\x9b\xbd'.decode('utf8'))
print(b'\xe4\xb8\xad\xe5\x9b\xbd'.decode('gbk'))
'''
Traceback (most recent call last):
  File "E:/python/character.py", line 15, in <module>
    print(b'\xe4\xb8\xad\xe5\x9b\xbd'.decode('gbk'))
UnicodeDecodeError: 'gbk' codec can't decode byte 0xad in position 2: illegal multibyte sequence
'''

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值