Python字符串操作

格式化

>>> print "Suzhou is more than %d years. %s lives in here." % (2500, "qiwsir")
Suzhou is more than 2500 years. qiwsir lives in here.

对于浮点数字的打印输出,还可以限定输出的小数位数和其它样式。

>>> print "Today's temperature is %.2f" % 12.235
Today's temperature is 12.23
>>> print "Today's temperature is %+.2f" % 12.235
Today's temperature is +12.23

 
 

>>> s1 = "I like {0}".format("python")
>>> s1
'I like python'
>>> s2 = "Suzhou is more than {0} years. {1} lives in here.".format(2500, "qiwsir") 
>>> s2
'Suzhou is more than 2500 years. qiwsir lives in here.'

这就是python非常提倡的string.format()的格式化方法,其中{索引值}作为占位符,

这种方法真的是非常好,而且非常简单,只需要将对应的东西,按照顺序在format后面的括号中排列好,分别对应占位符{}即可。我喜欢的方法。

如果你觉得还不明确,还可以这样来做。

>>> print "Suzhou is more than {year} years. {name} lives in here.".format(year=2500, name="qiwsir") 
Suzhou is more than 2500 years. qiwsir lives in here.


去掉字符串两头的空格


方法是:

  • S.strip() 去掉字符串的左右空格
  • S.lstrip() 去掉字符串的左边空格
  • S.rstrip() 去掉字符串的右边空格

split

这个函数的作用是将字符串根据某个分割符进行分割。

>>> a = "I LOVE PYTHON"
>>> a.split(" ")
['I', 'LOVE', 'PYTHON']

这是用空格作为分割,得到了一个名字叫做列表(list)的返回值,关于列表的内容,后续会介绍。还能用别的分隔吗?

>>> b = "www.itdiffer.com"
>>> b.split(".")
['www', 'itdiffer', 'com']

字符大小写的转换

        S.title() #S中的字符串首字母变成大写
  • S.upper() #S中的字母大写
  • S.lower() #S中的字母小写
  • S.capitalize() #首字母大写
  • S.isupper() #S中的字母是否全是大写
  • S.islower() #S中的字母是否全是小写
  • S.istitle() #S中字符串中所有的单词拼写首字母是否为大写,且其他字母为小写

join拼接字符串

>>> b
'www.itdiffer.com'
>>> c = b.split(".")
>>> c
['www', 'itdiffer', 'com']
>>> ".".join(c)
'www.itdiffer.com'
>>> "*".join(c)
'www*itdiffer*com'

 
 


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值