python 字符串与数据类型

字符串(string)是一个字符的系列

***表示方法:
    使用成对的单引号('')或者双引号(""")括起来
    或者三引号(''' 或者"""):保留字符串中的全部格式信息
    #注意:所有的引号都是成对存在
In [1]: s='nihao'

In [2]: s
Out[2]: 'nihao'

In [3]: b='''
   ...: The weather is so good today!
   ...: I am "xmj"!
   ...: '''

In [4]: b
Out[4]: '\nThe weather is so good today!\nI am "xmj"!\n'

In [5]: print b

The weather is so good today!
I am "xmj"!

*基本运算

1.长度(len()函数) #len(字符串):统计字符串的长度
2.拼接(+)     #一个字符串和一个整数无法执行拼接操作
3.重复(*)  #字符串/变量*num:num表示重复打印的次数,必须是整数
4.成员运算(in#判断一个字符串是不是另一个的子字符串,运算时有大小写之分
——>返回的值是布尔值: True 或者 False
5.for语句 #梅举字符串中的每个字符
In [8]: name=s+"beautiful"

In [9]: len(name)
Out[9]: 14

In [10]: s
Out[10]: 'nihao'

In [11]: name*3
Out[11]: 'nihaobeautifulnihaobeautifulnihaobeautiful'

In [15]: "nihao" in "nihaomingt"
Out[15]: True

In [17]: for char in name:
   ....:     print char
   ....:     
n
i
h
a
o
b
e
a
u
t
i
f
u
l

In [18]: 

编程示例:
统计出所给字符串中的元音字母的个数:

!!!代码块

#!/bin/env python
#coding:utf-8
s=raw_input("Please 输入一串字符:")
def yuanyin(s):
        count = 0
        for c in s:
                if c in "aeiouAEIOU":
                        count += 1
        return count

print ("您输入的字符串是:%s\n") %s
print "其中元音字母的个数是:%s" %(yuanyin(s))

>>>>>>>>>>>>>>>>>>>>>>>>>
!!!测试:
[root@foundation66 python]# python zifuchuan.py 
Please 输入一串字符:beautiful
您输入的字符串是:beautiful

其中元音字母的个数是:5
[root@foundation66 python]# 

*字符串索引

1.字符串中每一个字符都有一个索引值(下标)
2.索引从0(第一个)或 -1(最后一个)开始
3.索引运算符:[]      #str[number]
In [1]: b="nihao today"

In [2]: b[2]
Out[2]: 'h'

In [3]: b[-2]
Out[3]: 'a'

In [4]: len(b)
Out[4]: 11

*字符串切片

——>选择字符串的子序列
语法:  str[start:finish:countBy]
        start:子序列开始位置的索引值
        finish:子序列结束位置的前一个字符
        countBy:间隔数,默认值为1,若为-1 则为逆序
默认情况下:start为第0个字符开始,finish为最后一个字符串In [5]: b
Out[5]: 'nihao today'

In [6]: b[3:10:2]
Out[6]: 'a oa'

In [8]: b[::-1]
Out[8]: 'yadot oahin'

In [9]: 

*字符串是不可变的

1.字符串一旦生成,就不能通过下标的形式进行修改
2.只能通过切片的方法进行修改
In [9]: b
Out[9]: 'nihao today'

In [10]: b[2]='p'
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-10-ad945fb61fa4> in <module>()
----> 1 b[2]='p'

TypeError: 'str' object does not support item assignment

In [11]: b=b[:2] + 'p' +b[3:]

In [12]: print b
nipao today

In [13]: 

*字符串的方法

——>提供对象的函数
如:

b.replace(old,new)
#生成一个新的字符串,用new替换old,原字符串内容不变,若要改变原字符串,需要将新生成的字符串赋值给原字符串
In [16]: b
Out[16]: 'nipao today'

In [17]: b.replace("p","h")
Out[17]: 'nihao today'

In [18]:

b.find(要查找的字符串)
#返回值是第一次出现此字符串的下标
In [18]: b
Out[18]: 'nipao today'

In [19]: b.find("o")
Out[19]: 4

In [20]: 

b.split()
#对原始字符串进行切分
In [23]: b
Out[23]: 'nipao today'

In [24]: b.split()
Out[24]: ['nipao', 'today']

In [25]: b.
b.capitalize  b.format      b.isupper     b.rindex      b.strip
b.center      b.index       b.join        b.rjust       b.swapcase
b.count       b.isalnum     b.ljust       b.rpartition  b.title
b.decode      b.isalpha     b.lower       b.rsplit      b.translate
b.encode      b.isdigit     b.lstrip      b.rstrip      b.upper
b.endswith    b.islower     b.partition   b.split       b.zfill
b.expandtabs  b.isspace     b.replace     b.splitlines  
b.find        b.istitle     b.rfind       b.startswith  

In [25]: b.

编程示例:
读取人名的文件,将人名的输出格式打印成为首字母大写其余字母小写

对文件操作:
f=open('filename','mode')
        filename:文件名
        mode:r w等
for line in f:      #按行执行文件
        print  ...
f.close()   #关闭文件
f.write(str)    #写文件



!!!代码块:
#!/bin/env python
#coding:utf-8
f=open('name.txt','r')  

for line in f:
        line=line.strip()  #去掉一个字符串开始和结尾的空格|回车等
        print line.title()  #将字符串转化为首字母大写,其余字母小写的格式

f.close()       #关闭文件

!!!运行结果
[root@foundation66 python]# python name.py 
Aaadj
Jiui
Hjhygbf
Mouih
Vgfvj
Huou
Bjbk
Njkui
Ioujkju
[root@foundation66 python]# 

*字符串比较大小
任何一个字符都对应一个数字(ASCII)
直接比较对应数字的大小
字符串大小的比较:字典序 #逐位进行比较

!!!判断一个数是奇数还是偶数
#!/bin/env python
#coding:utf-8

x=input("请输入一个整数:")
print '偶数' if x%2==0 else '奇数'
#if x%2==0:
#       print "%s是偶数!" %x
#else:
#       print "%s是奇数!" %x

逻辑运算符
*and:与 #全真才真
*or:或 #全假才假
*ont:非 #真变假,假变真

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值