Python字符串操作


Python中,字符串是用引号括起来的一串字符,单引号(‘abc’)和双引号(“abc”)都是表示字符串。

1、split() ------字符串分割

定义:

S.split(sep=None, maxsplit=-1)  ->  list of strings

使用方法:
split()方法是以指定的字符为分割符,将字符串分割成多个元素,并保存在一个列表中(返回一个列表)。
如果不传参数,则默认以空格(‘ ’)为分割,同时可以将字符串两端的空格去掉:

>>> string = "  ab cd ef gh    "
>>> lst = string.split()
>>> lst
['ab', 'cd', 'ef', 'gh']

如果指定分割符,则以指定符号分割;如果指定了最大分割数maxsplit,则按maxsplit分割相应次数。

>>> string = "ab|cd|ef|gh"
>>> string.split('|')
['ab', 'cd', 'ef', 'gh']
>>> string.split('|', maxsplit=2)
['ab', 'cd', 'ef|gh']

2、format() ------字符串格式化

定义:

S.format(*args, **kwargs) -> str

使用方法:

# 不设置指定位置,按默认顺序
>>> "{} {}".format("hello", "world")
'hello world'
 
 # 设置指定位置
>>> "{0} {1}".format("hello", "world")
'hello world'    		

# 设置指定位置
>>> "{1} {0} {1}".format("hello", "world")
'world hello world'	

如果在字符串中需要直接展示花括号,则用另一个花括号包裹起来转义。

>>> "{{我是谁}}:{}".format("皮卡丘")
'{我是谁}:皮卡丘'

也支持参数式填写:

>>> "我是谁:{pikachu}".format(pikachu="皮卡丘")
'我是谁:皮卡丘'

数字格式化:
数字格式化

#数字格式化
>>> "{:.2f}".format(3.1415926)					
'3.14'

3、join() ------将可迭代对象转化为字符串

定义:

S.join(iterable)  ->  str

使用方法:
‘seq’.join(obj)
seq:为分隔符,可以为空;
obj: 一个可迭代对象,可以为列表,元祖,字典等。

>>> a = ["hello", "world", "!"]
>>> ' '.join(a)
'hello world !'

字典也可以转化为字符串。如果不写.values(),默认是将键拼接。

>>> b = {'a':'hello', 'b':'world'}
>>> ' '.join(b.values())
'hello world'

4、center() ------字符串居中

定义:
返回一个长度为width,两边用fillchar(单字符)填充的字符串,即字符串str居中,两边用fillchar填充。若字符串的长度大于width,则直接返回字符串str。
fillchar的默认字符为空格。

def center(self, width, fillchar=None):    ->  str

使用方法:

>>> a = 'hello'
>>> a.center(20,'*')
'*******hello********'

若字符串长度大于width,则返回原字符串。

>>> a = 'hello world!'
>>> a.center(10,'*')
'hello world!
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值