python2学习------基础语法

1、变量类型

Numbers(数字):int,float,long
String(字符串)
List(列表)
tuple(元组)
dict(字典)
bool(布尔):True,False

# 删除变量
 
del 变量名;

2、常用函数

<1> 输出信息
       print 输出信息;
<2> 交互
       raw_input('请输入内容'); 
<3> 类型转换
       int(x [,base])            将x转换为一个整数
       long(x [,base] )          将x转换为一个长整数
       float(x)                  将x转换到一个浮点数
       complex(real [,imag])    创建一个复数
       str(x)                     将对象 x 转换为字符串
       repr(x)                     将对象 x 转换为表达式字符串
       eval(str)                 用来计算在字符串中的有效Python表达式,并返回一个对象
       tuple(s)                 将序列 s 转换为一个元组
       list(s)                    将序列 s 转换为一个列表
       set(s)                     转换为可变集合
       dict(d)                     创建一个字典。d 必须是一个序列 (key,value)元组
       frozenset(s)             转换为不可变集合
       chr(x)                     将一个整数转换为一个字符
       unichr(x)                将一个整数转换为Unicode字符
       ord(x)                     将一个字符转换为它的整数值
       hex(x)                     将一个整数转换为一个十六进制字符串
       oct(x)                    将一个整数转换为一个八进制字符串
<4> 查看变量类型
       type(变量名)
<5> 查看与变量相关的函数
       dir(变量名)
<6> 查看变量某个函数的具体使用方式
       help(变量名.函数名)

3、注释

<1> # 
       # 注释内容
<2> '''
       '''
        注释内容1
        注释内容2
        ...
       '''
<3> """
       """
        注释内容1
        注释内容2
        ...
       """

4、字符串常用操作

<1> 长度
      a='test';
      print a.__len__(); #4
<2>获取子串
      a='test';
      print a[0:1]; # t
      print a[0:2]; # te
      print a[0:3]; # tes
      print a[0:4]; # test
      print a[0:5]; # test
      print a[:4]; # test
      print a[1:]; # est
      print a[1:3]; # es
print a[-1:]; # t
print a[-2:]; # st
print a[-3:]; # est
print a[-4:]; # test
print a[-3:-1]; # es
print a[-2:-1]; # s <3>判断是否存在某个字符以及出现的次数(大于0则存在) a='test'; print a.count('t');# 2 <4>重复扩展字符串 a='test'; a=a*2; print a; # testtest <5>分割字符串 a='test,测试'; a=a.split(','); print a; # ['test', '\xb2\xe2\xca\xd4'] type(a); # <type 'list'> <6>替换字符串 a='testtesttest'; a.replace('test','hello'); # hellohellohello a.replace('test','hello',1);# hellotesttest a.replace('test','hello',2);# hellohellotest a.replace('test','hello',3);# hellohellohello <7>转换为字节数组 a="abcabc"; a=list(a);#不去重 ['a','b','c','a','b','c'] a=set(a);#去重['a','b','c']
<8>转义特殊标识(如换行标识)
a='hello \n python';
b=r"hello \n python";
print a;# 分两行显示
print b;# hello \n python

5、字典常用操作

<1> 获取所有key值
    a={'name':'lxh','nation':'China'};
    print a.keys(); # ['name','nation']
<2> 获取所有value值
    a={'name':'lxh','nation':'China'};
    print a.values(); # ['name','nation'] 
<3> 获取指定key值
a={'name':'lxh','nation':'China'};
print a['name']; # lxh

6、待完善

猜你喜欢

转载自www.cnblogs.com/lvlin241/p/9438716.html