Python build-in数据类型之字符串str (一)

在Python里文本数据是用str字符串类型来实现,用单引号'或者双引号" 括起来的任意文本。

比如'abc', "123abc", 注: '''triple quotes''' 以及 """three double-quotes""" 也是有效的

>>> '''triple quotes'''
'triple quotes'

>>> """three double-quotes"""
'three double-quotes'

另外下面这种方式也是合法的,引号之间的空格会被忽略掉

>>> x = "mash " "potato " "tastes " "good"
>>> x
'mash potato tastes good'

 

字符串是不可更改类型,也就是说一旦初始化就不能修改

example:

>>> s = "ABCD"
>>> s[0]
'A'
>>> s[0] = 'F'   #尝试将首字符改成 F
TypeError: 'str' object does not support item assignment

 

string方法介绍

str.capitalize() --返回该字符串的拷贝,并将首字母大写,其余的小写 example:

>>> 'hEllO WORLD'.capitalize()
'Hello world'

str.lower() --返回该字符串的拷贝,所有字母小写

str.upper() --返回该字符串的拷贝,所有字母大写

str.casefold() --与lower()相似,也是返回小写,区别是lower()只对英文字母'A-Z'有效,但是其他语言中的小写情况就无效了,这时我们就需要用casefold()

example:德语里 'ß' 的小写是 'ss' 

>>> s = 'ß'
>>> s.lower()
'ß'
>>> s.casefold()
'ss'

str.center(width[, fillchar])

参数:width--指定返回字符串的宽度, fillchar用来填充的字符,默认是空格

返回值:返回一个指定宽度的字符串,原字符串置于中间,收尾用fillchar填充,如果指定的宽度小于或等于原字符串的长度,则返回原字符串

example:

>>> s= 'abc'
>>> s.center(10)
'   abc    '
>>> s.center(3)
'abc'
>>> s.center(7,'s')
'ssabcss'
>>> s.center(9, '#')
'###abc###'

str.count(sub, start = 0, end = len(str))--返回某个字符在字符串中指定的范围内出现的次数,默认起始位置是0,结束位置是len(str)。

str.encode(encoding='utf-8', error='strict')--以指定的编码方式编码字符串,默认是utf-8, error指定不同的错误处理方案。

str.decode(encoding='utf-8', error='strict')--以指定的编码方式解码字符串

example:

>>> s = '你好'
>>> s.encode()
b'\xe4\xbd\xa0\xe5\xa5\xbd'
>>> s.encode('gb2312', 'strict')
b'\xc4\xe3\xba\xc3'
>>> x = b'\xc4\xe3\xba\xc3'
>>> x.decode('gb2312', 'strict')
'你好'

str.endswith(suffix[, start[, end]])--判断字符串是否以指定字符串sufix结尾,返回True,False。start、end指定检索范围,默认start = 0, end = len(str)。sufix可是一个字符串,也可以是一个字符串元组。

example:

>>> s = '人生苦短,我用Python'
>>> s.endswith('on')
True
>>> s.endswith('on', 2, 6)
False
>>> s.endswith(('n', '', ''),2,5)
False
>>> s.endswith(('n', '', ''),2,6)
True

>>> s.endswith('n',0,13)
True
>>> s.endswith('n',0,12)
False

 

转载于:https://www.cnblogs.com/aaron-zhao/p/6650821.html

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值