格式化
>>> 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'