武sir第二讲(2)基本数据类型

一、 数字

int(整形)

      在32位机器上,整数的位数为32位,取值范围为-2**31~2**1-1,即-21474836482147483647
在64位系统上,整数的位数为64位,取值范围为-2**63~2**63-1,即-9223372036854775808~9223372036854775807

++++++++++++++++++++++++++++++++++++++++++++++++++++

def bit_length(self):

“””表示返回该数字的二进制占用的最小位数”””

int.bit_length()-> int

案例:

int_bit = 37
ret = int_bit.bit_length()
print(ret)



答案:6
<span style="font-family:FangSong_GB2312;font-size:18px;">(解释过程){
>>> bin(37)
 '0b100101'
 >>> (37).bit_length()
        6
 """
}
</span>

二、字符串的参数(常用功能:移除,分割,长度,索引,切片)

1、

1defcapitalize(self):

“””首字母大写”””

案例:
<span style="font-family:FangSong_GB2312;font-size:18px;">acc = “alex”
ret = acc.capitalize()
print(ret)
</span>

2defcenter(self,width,fillchar=None):

   “””内容居中,width:总长度;filchar:空白处填充内容,默认无 ”””

S.center(width[,fillchar]) -> string

案例一:

<span style="font-family:FangSong_GB2312;font-size:18px;">al = "acc"
ret = al.center(20)
print(ret)
结果默认是空格
      acc     
</span>

案例二:
<span style="font-family:FangSong_GB2312;font-size:18px;">al = "acc"
ret = al.center(20,"_")
print(ret)
结果:________acc_________
</span>


3def count(self,sub,start=None,end=None)

“””子序列个数”””

s.count(sub[,start[,end]])  -> int

案例:
<span style="font-family:FangSong_GB2312;font-size:18px;">acc = "alexadal"
ret = acc.count("al")
re = acc.count("al",2,10)
print(ret)
print(re)
 答案:2     1
</span>

4defdecode(self,encoding=None,errors=None)

“””解码”””

 s.decode([encoding[,errors]])  -> object

案例:

<span style="font-family:FangSong_GB2312;font-size:18px;">temp = “李杰”
temp_unicode = temp.decode(‘utf-8’)
意思是把utf-8解码成unicode
</span>

5defencode(self, encoding=None, errors=None): 

 """编码,针对unicode """

 """

S.encode([encoding[,errors]])-> object

案例:

temp.gpk = temp.unicode(‘gbk’)

意思是把unicode在编码成gbk格式

6defendswith(self,suffix,start=None,end=None)

“””是否以xxx结束”””

s.endswith(suffix[,start[,end]]) ->bool

 案例:

<span style="font-family:FangSong_GB2312;font-size:18px;">name_a = "accp"
ret = name_a.endswith("ac",0,2)
print(ret)
   结果:True
</span>


7defexpandtabs(self,tabsize=None)

“””将tab转换成空格,默认一个tab转换成8个空格”””

 s.expandgtabs([tabsize]) -> string

 案例:

<span style="font-family:FangSong_GB2312;font-size:18px;">name_b = "this is a \tasdf"
ret = name_b.expandtabs()
ac = name_b.expandtabs(tabsize=10)
print(ret)
print(ac)
结果:
this is a       asdf
this is a           asdf
</span>

8deffind(self,sub,start=None,end=None):

“””寻找子序列位置,如果没有找到,返回 -1”””

s.find(sub[,start[,end]]) -> int

·  str -- 查找的字符串

·  beg -- 开始查找的位置,默认为0

·  end -- 结束查找位置,默认为字符串的长度

      案例:

<span style="font-family:FangSong_GB2312;font-size:18px;">str1 = "this is a string example ... wow"
str2 = "exam"
print(str1.find(str2))
print(str1.find(str2,10))
print(str1.find(str2,40))
答案:17	
17
-1  ----错误了find参数用-1表示,而index是报错
str = "this is really a string example....wow!!!";
str1 = "is";
print str.rfind(str1, 0, 10);
</span>

9def indexself,sub,start=None,end=None:

“””子序列位置,如果没找到,报错”””

 s.index(sub[,start[,end]]) ->int

案例:

<span style="font-family:FangSong_GB2312;font-size:18px;">str1 = "this is a string example ... wow"
str2 = "exam"
ret = str1.index("strin",3)
print(ret)
print(str1.index(str2,10))
答案:10
      17
</span>


和find一样,相对应的也有rindex

<span style="font-family:FangSong_GB2312;font-size:18px;">#!/usr/bin/python3
str1 = "this is really a string example....wow!!!"
str2 = "is"

print (str1.rindex(str2))
print (str1.rindex(str2,10))
------------------------------------------
5
Traceback (most recent call last):
  File "test.py", line 6, in <module>
    print (str1.rindex(str2,10))
ValueError: substring not found
</span>


10def format(*args,**kwargs):

  “””字符串格式化,动态参数,将函数式编程时细说”””

 s.format(*args,**kwargs)-> string

案例:

<span style="font-family:FangSong_GB2312;font-size:18px;">s = "hello {0},world(1)"
print(s)
new1 = s.format("alex",19)
print(new1)
答案:hello {0},world(1)
hello alex,world(1)
</span>

案例二、

<span style="font-family:FangSong_GB2312;font-size:18px;">•	{name}:将被format()方法中关键字参数name代替
        >>> print '{c} {b} {a}'.format(a = 'efhdn', b = 123, c = 8.3 )
        8.3 123 efhdn
•	{或}:要输出一个{或},必须使用{{或}}格式
        >>> print '{{中国}} 你好!'.format()
        {中国} 你好!
</span>

11defisalnum(slef):

              “”””是否是字母和数字””

              s.isalnum()  ->bool

       案例:
<span style="font-family:FangSong_GB2312;font-size:18px;">str = "this2009";  # No space in this string
print str.isalnum();

str = "this is string example....wow!!!";
print str.isalnum();
答案:
True
False
</span>


12defisalpha(self):

           “””是否是字母”””

 s.isalpha()-> bool

13defisdigit(self):

 “””是否是数字”””

s.isdigit() -> bool

14defislower(self):

   “””是否小写”””

   s.islower()-> bool

15def isspace(self):

   “””是否只包含空格”””

s.isapce() -> bool

案例:

<span style="font-family:FangSong_GB2312;font-size:18px;">str = "       "; 
print str.isspace();

str = "This is string example....wow!!!";
print str.isspace();
</span>

16defistitle(self):

“””检测字符串中所有的单词拼写首字母是否为大写,且其他字母为小写返回True,否则为False”””

a = “This Is A Sjsd”

a.istitle()  à bool

17defisupper(self):

  “””检测字符串是否为大写”””

s.isupper() -> bool

18defjoin(self,itearble):

   “””连接”””

      s.join(iterable) -> string

案例:

<span style="font-family:FangSong_GB2312;font-size:18px;">str1 = "_*"
str2 = ("a","b","c")
ret = str1.join(str2)
print(ret)
答案:a_*b_*c
</span>

19defljust(self,width,fillchar=None):

 “””内容左对齐,右侧填充”””

s.ljust(width[,fillchar]) -> string

width ----指定字符串长度

fillchar----填充字符,默认为空格

案例:

<span style="font-family:FangSong_GB2312;font-size:18px;">str = “this is sting exaple…wow”
ret = str.ljust(30,’*’)  #注意这个的fillchar要加引号,引起来
print(ret)
答案:
this is sting exaple…wow*******
		相对应的有函数rjust(右对齐,左填充),方法一样
zfill也一样
 def zfill(self, width):  
 """方法返回指定长度的字符串,原字符串右对齐,前面填充0。"""

 S.zfill(width) -> string
</span>

20deflower(self):

“””变小写”””

s.lower() -> string

案例:

str_name1 = "MY NAME IS damon"
print(str_name1.lower())
答案:
my name is damon
相对应的是upper““变大写”
up = "this is string example ...wow"
ret = up.upper()
print(ret)
答案
THIS IS STRING EXAMPLE ...WOW

21defpartitiong(self,sep):

“””””分割,前,中,后三部分”

s.partition(sep) -> (head,sep,tail)

案例:

str_name1 = "MY NAME IS domen"
ret = str_name1.partition("IS")
print(ret)
答案:
('MY NAME ', 'IS', ' domen')

22def lstrip(self,chars=None):

“””移除左侧空白”””

s.lstrip([chars]) -> string or unicode

chars 表示指定截取的字符

案例:

str_name2 = "    this is a string wow ...."
print(str_name2.lstrip())
str_name3 = "88888this is a string wow ... 888"
print(str_name3.lstrip("88888this"))
答案:
this is a string wow ....
 is a string wow ... 888

23def replace(self,old,new,coubt=None):

“”””替换””

s.replace(old,new[,count]) -> int

s.replace(old,new[,count]) -> int

s.replace(old,new[,count]) -> int

old 将被替换的子字符串

new 新字符串,用于替换old子字符串

max 可选字符串,替换不超过max次

案例:

str_name3 = "this is a example wow,this is a really example,is"
ret = str_name3.replace("is","si",2)
print(ret)
答案:
thsi si a example wow,this is a really example,is

24defsplit(self,sep=None,maxsplit=None):  _—————join相反(join是连接)

“””分割,maxsplit最多分割几次”””

s.split([sep[,maxsplit]]) -> list of strings

str – 分隔符,默认为空格

num – 分割次数

案例:

str = "Line1-abcdef \nLine2-abc \nLine4-abcd";
print(str.split( ))
print(str.split(' ', 1 ))
print(str)
答案:
['Line1-abcdef', 'Line2-abc', 'Line4-abcd']
['Line1-abcdef', '\nLine2-abc \nLine4-abcd']
Line1-abcdef 
Line2-abc 
Line4-abcd

25defsplitlines(self,keepends=False):

   “””根据换行分割”””

S.splitlines(keepends=False) -> list of strings

案例:

str_name5 = "this is a example wow \n yes,zhis is \n\n\n\n i don't"
print(str_name5.splitlines(3))
答案:
['this is a example wow \n', ' yes,zhis is \n', '\n', '\n', '\n', " i don't"]

26defstartswith(self,prefix,start=None,end=None):

“””是否起始”””

S.startswith(prefix[,start[,end]]) -> bool

案例:

str = "i like you "
ret = str.startswith("i",0,4)
print(ret)
答案:True

27defstrip(self,chars=None):

“””移除两段空白”””

S.strip([chars]) -> string or unicode

案例:

str = "*****this is string example....wow!!!*****"
print (str.strip( '*' ))
答案:
this is string example....wow!!!

28defswapcase(self):

“”大写变小写,小写变大写””

S.swapcase() -> string

案例:

bxx = "THIS IS A EXSMPLE.."
ret = bxx.swapcase()
print(ret)
答案:
this is a exsmple..

29deftitle(self):

“””开头首字母变大写”””

S.title() -> string

案例:

tit = "THIS IS A EXSMPLE.."
ret = tit.title()
print(ret)
答案:
This Is A Exsmple..

30deftranslate(self,table,deletachars=None):--3.0没有deletachars这个参数了

“转换需要先做一个对应表,最后一个表示删除字符集合”

  • table -- 翻译表,翻译表是通过maketrans方法转换而来。
  • deletechars -- 字符串中要过滤的字符列表。

S.translate(table[,deletechars]) -> string

案例:

intab = "aeiou"
outab = "12345"
transtab = str.maketrans(intab,outab)
str = "this is a string example ... wow"
ret = str.translate(transtab)
print(ret)
答案:
th3s 3s 1 str3ng 2x1mpl2 ... w4w

知识小点:

maketrans() 方法用于创建字符映射的转换表,对于接受两个参数的最简单的调用方式,第一个参数是字符串,表示需要转换的字符,第二个参数也是字符串表示转换的目标。

注:两个字符串的长度必须相同,为一一对应的关系。


maketrans用法

str.maketrans(intab,outab)

参数:

intab – 字符串中药代替的字符组合的字符串

outab – 相应的映射字符的字符串

三、列表(基本操作:索引,切片,追加,删除,长度,切片,循环,包含)

创建列表:name_list = [‘alex’,’serven’,’eric’]

或 name_list = list([‘alex’,’serven’,’eric’])

1、 def append(self,p_object):

“”末尾添加””

语法:L.append(object) -----obj—添加到列表末尾的对象

案例:

list1 = ['google','baidu','nunoob']
list2= list1.append('tengxun')
print("更新后的列表 ",list1)#注:list2已经执行添加到了列表,打印出来肯定为空
答案:
更新后的列表  ['google', 'baidu', 'nunoob', 'tengxun']

2、def count(self,value):

“”统计某个元素在列表中出现的次数””

语法:list.count(obj) ---obj—列表中统计的对象

案例:

alist = [123,'xyz','zara','abc']
print('次数',alist.count(123))
print('次数:',alist.count('xyz'))
答案:
次数 1
次数: 1

3、def extend(self,iterable): 新单词extend(扩展)

“””用于在列表末尾一次性追加另一个列表中的多个值(用新列表扩展原来的列表)”””

语法:list.extend(seq---元素列表)

案例:

list1 = ['google','runoob','taobao']
list2 = list(range(5))
list1.extend(list2)
print('扩展后的列表:',list1)
答案:
扩展后的列表: ['google', 'runoob', 'taobao', 0, 1, 2, 3, 4]

4def index(self):

“””用于从列表中找出某个值第一个匹配项的索引位置”””

语法:list.index(obj—查找的对象)

案例:

alist = [123,'xyz','zara','abc']
print("Index for xyz:",alist.index('xyz'))
print('Index for zara',alist.index('zara'))
答案:
Index for xyz: 1
Index for zara: 2

5def insert(self,index,p_object):

“””函数将用于指定对象charu 列表”””

语法:list.insert(index,obj)

index,对象obj需要插入的索引位置

obj,要出入列表中的对象

案例:

list1 = ['google','baidu','ali']
list1.insert(1,'lol')
print('列表插入元素后:',list1)
答案:
列表插入元素后: ['google', 'lol', 'baidu', 'ali']

6defpop(self,index=None):

“””用于移除列表中的一个元素(默认最后一个元素)”””

语法:list.pop(obj=list[-1])

案例:

list1 = ['google','baidu','ali']
list1.pop()
print(list1)
list1.pop(-1)
print(list1)
答案:
list1 = ['google','baidu','ali']
list1.pop()
print(list1)
list1.pop(-1)
print(list1)

7def remove(self,value)

“””用于移除列表中的某个值的第一个匹配项”””

语法:list.remove(obj)

案例:

list_rm = ['google','baidu','ali']
list_rm.remove('google')
print(list_rm)

8defreverse(self):

“””用于反向列表中的元素”””

语法:list.reverse()

      案例:

list1 = ['baidu','google','ali','tengx']
list1.reverse()
print('见证奇迹的时刻:',list1)

9defsort(self,cmp=None,key=None,reverse=False):

“””用于对原列表进行排序,如果指定参数,则使用比较函数指定的比较函数”””

语法:list.sort([func])

func ---可选参数,如果指定了该参数会使用该参数的方法进行排序

案例:

list1 = ['ali','Ali','Google','BAIDU','12']
list1.sort()
print(list1)
结果:


四、元组(tuple)

基本操作:索引、切片、循环、长度、包含


创建元组:

ages = (11,22,33,44,55)

ages = tuple((11,22,33,44,55))

内置函数:count和index

案例:

tup_1 = (11,22,33)
print(tup_1.count(33))
print(tup_1.index(22))
答案:1    1
五、字典

1clear

“”“用于删除字典内的所有元素”“”

语法:dict.clear()

           案例:

dict = {'name':'zara','age':7}
print('start len:%d' % len(dict))
dict.clear()
print('start len :%d' % len(dict))
答案:
start len:2
start len :0

2get

“”“函数返回指定键的值,如果值不在字典中返回默认值”“”

语法:dict.get(key,default=None)

参数:key ---字典中要查找的键

default – 如果指定键的值不存在时,返回该默认值

案例:

dict = {'google':'am','baidu':'chi','ali':'chi'}
print("值为:%s" % dict.get('google'))
print("值为:%s" % dict.get('yutube','em'))---如果字典中没有则添加
答案:值为:am
值为:em

3in

“in操作符用于判断是否存在于字典中,如果键在字典dict里返回True,否则返回False”

语法:key in dict

案例:

dict = {'name':'alex','age':'18'}
ke = 'age'
kee = 'max'
if ke in dict:
    print("age的值存在")
else:
    print("age的值不存在")
if max in dict:
    print('max的值存在')
else:
    print('max的值不存在')
答案: age的值存在
max的值不存在

4keys

”“”python字典keys()方法以列表返回一个字典所有的键“”“

语法:dict.keys()

案例:
<pre name="code" class="python">dict ={'name':'runoob','age':'3'}
dict2 = dict.keys()
print(dict2)
答案:
dict_keys(['name', 'age'])


 

5pop

“”“同list一样,删除”“

dict = {'name':'runoob','age':'3'}
dict2 = dict.pop('age')
print(dict2)
print(dict)
答案:3
{'name': 'runoob'}

7、uptade

”“”函数把字典dict2的键/值对更新到dict里(前面)“”“

语法:dict.update(dict2)

案例:

dict = {'name':'alex','age':'3'}
dict2 = {'max':'man'}
dict.update(dict2)
print('更新后的字典:',dict)
答案:
{'max': 'man', 'name': 'alex', 'age': '3'}





  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值