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

Python学习-String(一)

2015-07-25 04:43 465 查看

Python学习-String(一)

你将学到Python语言中关于string的用法

注意: #在Python中string 对象是不可变的,任何对string对象的操作实质上都会产生一个新的string对象

1.新建string对象

用双引号或者单引号来实例化一个新的string对象,例如:

s1 = "Hello world!"
s2 = 'Hello world!'


存在双引号和单引号是为了:可以相互包含着使用

s1 = "Hello 'Earth'!"
s2 = 'Hello "Kepler"!'
print s1
print s2


Hello 'Earth'!
Hello "Kepler"!


2.获得string的长度

s1 = "Hello world!"
print len(s1)


12


3.连接两个string

print "XO" + "xo"


XOxo


4.产生多个string

print "XO" * 10


XOXOXOXOXOXOXOXOXOXO


5.string的大小写问题

使用built-in函数

print "HFAJDKDH"
print "the lower case is " + "HFAJDKDH".lower()
print "the upper case is " + "hfajdkdh".upper()


HFAJDKDH
the lower case is hfajdkdh
the upper case is HFAJDKDH


6.判断一个string是否全部是数字

使用built-in函数

sf = "2345abcd"
se = ""
st = "12134"
print sf + " is whole digit? " + str(sf.isdigit())
print se + " is whole digit? " + str(se.isdigit())
print st + " is whole digit? " + str(st.isdigit())


2345abcd is whole digit? False
is whole digit? False
12134 is whole digit? True


7.计算string中字符、字符串的个数

使用built-in函数

sc = "Couuuuuuuunnnt cooooonntent"
print "# of o in " + sc + " is " + str(sc.count('o'))
print "# of ou in " + sc + " is " + str(sc.count('ou'))


# of o in Couuuuuuuunnnt cooooonntent is 6
# of ou in Couuuuuuuunnnt cooooonntent is 1


8.把string转化成list对象

sl = "abcdefghijklmnopqrstuvwxyz"
liststr = list(sl)
print liststr


['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: