python之字符串str的基本用法

定义:字符串就是由任意字符任意个数组成的有限序列

任意字符:字母,数字,特殊符号,中文

注意:字符串也是一种不可变的数据类型,字符串可以充当字典的key

工作原理:一个字符串的底层维护了一个由字符组成的元组,如:“hello‘----->(’h‘,‘e’,‘l’,‘l’,‘o’)

基本用法

dir(str)
['__add__', '__class__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mod__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmod__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'capitalize', 'casefold', 'center', 'count', 'encode', 'endswith', 'expandtabs', 'find', 'format', 'format_map', 'index', 'isalnum', 'isalpha', 'isdecimal', 'isdigit', 'isidentifier', 'islower', 'isnumeric', 'isprintable', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'maketrans', 'partition', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill']

接下来,直接举例。

1.大小写转换

s = 'Hello, World'
s.upper()
'HELLO, WORLD'
s.lower()
'hello, world'
s.swapcase()	#大写转小写,小写转大写
'hELLO, wORLD'
s.title()	#每个单词的首字母大写
'Hello, World'
s.capitalize()	#首单词的首字母大写
'Hello, world'

2.判断开头与结尾

s = 'Hello, World'
s.startswith('h')	#判断一个字符串是否是以指定子字符串开头
False
s.endswith('d')		#判断一个字符串是否是以指定子字符串结尾
True

3.切割与合并

s1 = 'good,better,best'
s1.split(',')
['good', 'better', 'best']
'--'.join(s1.split(','))
'good--better--best'

4.填充与移除

s = 'Hello, World'
s.center(30)
'         Hello, World         '
s.center(30,'*')		#使字符串居中
'*********Hello, World*********'
s.center(30,'*').strip('*')		#移除一个字符串两端的指定字符
'Hello, World'
s.center(30,'*').lstrip('*')    #移除一个字符串左边的指定字符
'Hello, World*********'
s.center(30,'*').rstrip('*')	#移除一个字符串右边的指定字符
'*********Hello, World'

s.ljust(30,'*')
'Hello, World******************'
s.rjust(30,'*')
'******************Hello, World'
s.zfill(30)		#默认填充0
'000000000000000000Hello, World'

5.替换

s
'Hello, World'
s.replace('World','jack')  #replace(old,new)
'Hello, jack'

6.索引查找

s
'Hello, World'
s.index('o')
4
s.rindex('o')
8
s.index('a')   #查不到报错
Traceback (most recent call last):
  File "<input>", line 1, in <module>
ValueError: substring not found
s.find('o')
4
s.rfind('o')
8
s.find('a')		 #查不到返回-1
-1

7.编解码

s
'Hello, World'
s.encode('utf8')	#编码,将字符串转化为字节类型【str--->bytes】
b'Hello, World'
a = s.encode('utf8')
a.decode('utf8')   	#解码,将字节类型转换为字符串【bytes---->str】
'Hello, World'

8.其他

eval('1+2')        #将str转换为有效的表达式
3
eval('1==2')
False

后续有待补充,望大家批评指正!

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值