您的位置:首页 > 编程语言 > Python开发

Python字符串学习4

2016-05-27 17:14 483 查看
字符串格式化输出

字符串格式化,就是要先制定一个模板,在这个模板中某个或者某几个地方留出

空位来,然后再那些空位填上字符串。那么,那些空位,需要用一个符号来表示

,这个符号通常被叫做占位符(仅仅是占据着那个位置,并不是输出的内容)。

>>> "I like %s"

'I like %s'

%s,就是一个占位符,这个占位符可以被其它的字符串代替。

>>> "I like %s" % "python"

'I like python'

占位符     说明

%s         字符串(采用str()的显示)

%r         字符串(采用repr()的显示)

%c         单个字符

%b         二进制整数

%d         十进制整数

%i         十进制整数

%o         八进制整数

%x         十六进制整数

%e         指数(基底写为e)

%E         指数(基底写为E)

%f         浮点数

%F         浮点数,与上相同

%g         指数(e)或浮点数(根据显示长度)

%G         指数(E)或浮点数(根据显示长度)

>>> a = "%d years" % 15

>>> print a

15 years

>>> 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

在python中新的格式化方法

>>> s1 = "I like {0}".format("python")

>>> s1

'I like python'

>>> s2 = "Suzhou is more than {0} year. {1} lives in here.".format

(2500,"qiwsir")

>>> s2

'Suzhou is more than 2500 year. qiwsir lives in here.'

这就是python非常提倡的string.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.

字典格式化:

>>> lang = "python"

>>> print "I love %(program)s"%{"program":lang}

I love python

常用的字符串方法

字符串的方法很大。可以通过dir来查看:

>>> dir(str)

>>> "python".isalpha() #字符串全是字母,应该返回True

True

>>> "python".isalpha() #字符串全是字母,应该返回False

False

split

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

>>> a = "I LOVE PYTHON"

>>> a.split(" ")

['I','LOVE','PYTHON']

这是用空格作为分割,得到了一个名字叫做列表(list)的返回值。

还有别的分隔符

>>> b = "www.itdiffer.com"

>>> b.split(".")

['www','itdiffer','com']

去掉字符串两头的空格

S.strip()去掉字符串的左右空格

S.lstrip()去掉字符串的左边空格

S.rstrip()去掉字符串的右边空格

例如:

>>> b=" hello "  #两边有空格

>>> b.strip()

'hello'

>>> b

' hello '

字符大小写的转换

S.upper()#S中的字母大写

S.lower()#S中的字母小写

S.capitalize()#S首字母大写

S.isupper()#S中的字母是否全是大写

S.islower()#S中的字母是否全是小写

S.istitle()#S中字符串中所有的单词拼写首字母是否为大写,且其他字母为小



>>> a = "This is a Book"

>>> a.istitle()

False

>>> b = a.title()  

>>> b

'This Is A Book'

>>> b.istitle()

True

join 拼接字符串

>>> b 

'www.itdiffer.com'

>>> c = b.split(".")

>>> c

['www','itdiffer','com']

>>> ".".join(c)

'www.itdiffer.com'

>>> "*".join(c)

'www*itdiffer*com'
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  Python