Python笔记——字符串的用法

字符串:

1、字符串不可变

>>> a

'this is a test'
>>> a[0:3]
'thi'
>>> a[0]='1'


Traceback (most recent call last):
  File "<pyshell#96>", line 1, in <module>
    a[0]='1'
TypeError: 'str' object does not support item assignment

>>> 


2、使用元组对字符串格式化:

>>> "this is a %s %s" % ("python","programer")
'this is a python programer'

>>> from math import pi
>>> "%s is %.10f" % ("pi",pi)
'pi is 3.1415926536'

     使用string 中的 Tamplate 模板替换

>>> from string import Template
>>> s=Template("$$,${x}is,is test")
>>> s.substitute(x='th')
'$,this,is test'
>>> "%s is %020.10f" % ("pi",pi)

'pi is 000000003.1415926536'
>>> "%s is %-020.10f" % ("pi",pi)
'pi is 3.1415926536        '
>>> 


3、字符串中的常量

string.digits 0-9数字

           .letters 所有字母

           .lowercase  所有小写字母

           .uppercase 所有大写字母

           .punctutation 所有标点符号

引用方法:

>>> from string import digits as d
>>> d
'0123456789'


4、find方法:返回要找字符串最左端的位置,没有找到则返回-1

>>> "this is the test".find("is")
2
>>> "this is the test".find("she")
-1


5、join方法:字符串连接方法,格式:连接字符串.join(["字符串元素1","字符串元素1","字符串元素1"]).  注意连接符和列表元素必须都为字符串.  返回一个连接后的字符串,它的反方法为split

 >>> a=["this","is","the","test"]
>>> " ".join(a)
'this is the test'
>>> a=[1,2,3]
>>> " ".join(a)
Traceback (most recent call last):
  File "<pyshell#124>", line 1, in <module>
    " ".join(a)
TypeError: sequence item 0: expected string, int found
>>> "the".join(["this","is"])
'thistheis'
>>> 


6、split方法:'需要拆分的字符串'.split('拆分字符串的标志符') 返回一个列表

>>> 'this is the test'.split(' ')
['this', 'is', 'the', 'test']
>>> '0+2+4+6+8'.split('+')
['0', '2', '4', '6', '8']
>>> 


7、lower()方法:将字符串中的大写字母转换成小写字母

>>> "This Is thE TEsT".lower()
'this is the test'


8、replace方法:格式  字符串.replace('原子符','替代字符')

>>> "This Is thE TEsT".lower().replace('is','ezz')   %从左往右计算
'thezz ezz the test'


9、strip方法:把两边的空格符删除

>>> '       this is the test                '.strip()
'this is the test'


10、另一种替换方法,单字符替换方法 translate,格式先用maketrans制作表,然后在进行替换

>>> from string import maketrans
>>> table=maketrans('cs','kz')     %c变为k,  s变为z

>>> 'this is a test'.translate(table)
'thiz iz a tezt'
>>> 'thiS is a test cd..'.translate(table)
'thiS iz a tezt kd..'











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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值