Python学习-String(一)

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']
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值