DAY03

时间:2019-10-03
本文章向大家介绍DAY03,主要包括DAY03使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

这里我们对python中的数据类型进行一个详细的解释。

一:数据类型:

       int(整形) 1,2,3                                              等等主要是用于计算

       bool(布尔类型):  Ture,False,                      主要用于用户进行判断

       str(字符串类型):  '胡澳'    "胡澳"                 存储少量数据进行操作

       list(列表):                [1,2,'huao',[1,2,3] ]          存储大量的数据。可读可写

       tuple(元组):            (1,2,"胡澳")                      也是用来进行存储数据,但是只读,不能修改,只能查看。(主要用来存储一些比较重要的数据,比如银行的账户余额,我们就只能进行查看,不能进行修改)

       dict(字典) :              {'name':"胡澳",'age':"18" }

                                      {”胡澳“:[age,grade],   "赵润全":[age,grase]}    字典也是用来存储数据的,像数据库里面的键和值一样,一个键对用一个值,或者一列值。

       gather集合:          {1,2,'33huao'}                   集合用的一般比较少,这里就不仔细觉得讲解了          

整形(int):

       整形一些常见的方法

       bit_length()

代码演示:

#bit_length()
a = 3
b = a.bit_length()
print(b)

运行结果:

D:\常用软件\Python3.7\python文件\python.exe D:/学习资料/项目/练习/lianxi.py
2

解析:显示2的原因是 3 用二进制表示为 0000 0011 在二进制中3只占有两位,所以程序运行结果为2。这就是为什么结果为2的原因

整型的用法比较少,这里主要对字符串的功能进行讲解进行讲解

字符串(str): 

         字符串的索引:              

a = "ABCD"
print(a[1])  #从左往右输出字符串中被指定的字符
print(a[-1]) #从右往左输出字符串中被指定的字符
'''
值得注意的是:从左往右的时候,最开始的是0
            从右往左的时候,最开始的是-1而不是0
'''

        字符串的切片:

a = "ABCDEFG"
a1 = a[0:3] #切片[a:b] a,b表示切取的字符区间,一般都是顾头不顾腚就相当于是[a:b)
a2 = a[0:4:2] #最后一位2,表示切取的步长,两个两个的切取
a3 = a[:] #当两边什都不加的时候表示从左到右全部输出
a4 = a[0:] #左边加0和两边什么都不加一个样子,都是表示从左到右全部输出
a5 = a[:-1] #右边加-1表示从右边输出到最左边,但是由于顾头不顾尾的原因说是所以最右边的G不能够输出
a6 = a[0:0] #起始0终止0所以输出的是空格只是看不出来而已
print(a1)
print(a2)
print(a3)
print(a4)
print(a5)
print(a6)

     运行结果:

D:\常用软件\Python3.7\python文件\python.exe D:/学习资料/项目/练习/lianxi.py
ABC
AC
ABCDEFG
ABCDEFG
ABCDEF

    字符串的开头(startswith)以及结尾(endswith):

a = "ABCDEFG"
'''
def startswith(self, prefix, start=None, end=None):
prefix表示前缀,start,end表示开始查找的范围.startswith返回的值是bool类型
'''
a1 = a.startswith('A')        #在整个字符串中查找有没有以A开头的字符
a2 = a.startswith('c',3,5)    #在索引3,5中查找有没有以C开头的字符
print(a1)
print(a2)

''' def endswith(self, suffix, start=None, end=None): suffix表示后缀,其余的和startswith一样 ''' a3 = a.endswith('d') a4 = a.startswith('f',1,2) print(a3) print(a4)

运行结果:

D:\常用软件\Python3.7\python文件\python.exe D:/学习资料/项目/练习/lianxi.py
True
False

False False 进程已结束,退出代码0

  字符串的find和index索引:

   Find

'''
def find(self, sub, start=None, end=None): # real signature unknown; restored from __doc__
        """
        S.find(sub[, start[, end]]) -> int

        Return the lowest index in S where substring sub is found,
        such that sub is contained within S[start:end].  Optional
        arguments start and end are interpreted as in slice notation.

        Return -1 on failure.
        """
        return 0

sub:查找的字符串
start和end 表示查找区间
该方法返回的是所在字符的索引,也就是整型
'''
a = "ABCDEFG"
a1 = a.find('A')      #在整个字符串查找A
print(a1)            
a2 = a.find('CD')     #在整个字符串查找CD
print(a2)
a3 = a.find('E',1,3)  #在索引为1,3的区间查找E的字符串
print(a3)
a4 = a.find('a')      #查找a
print(a4)
a5 = a.find('cd')     #查找cd
print(a5)

运行结果:

D:\常用软件\Python3.7\python文件\python.exe D:/学习资料/项目/练习/lianxi.py
0
2
-1
-1
-1
Return -1 on failure.   #find方法中写到的,当没找的到的时候会返回-1而不是错误。

   由运行结果可以看出,当查找不到字符串的时候,find会返回 -1 而不是直接报错或者抛出异常,这和find方法中说明的一样。

Return the lowest index in S where substring sub is found

在find方法描述中这样的一句话的意思是说:当找到字符串的时候会返回字符串的最小索引。
因为字符可能不只是一个字符,它也可能是像CD这样的一组字符。而如果查找到的话,直接返回的是C的索引,也就是返回字符串的最小索引

    index

   代码演示: 

'''
def index(self, sub, start=None, end=None): # real signature unknown; restored from __doc__
        """
        S.index(sub[, start[, end]]) -> int

        Return the lowest index in S where substring sub is found,
        such that sub is contained within S[start:end].  Optional
        arguments start and end are interpreted as in slice notation.

        Raises ValueError when the substring is not found.
        """
'''
a = "ABCDEFG"
a1 = a.index('A')      #在整个字符串查找A
print(a1)
a2 = a.index('CD')     #在整个字符串查找CD
print(a2)
a3 = a.index('E',1,3)  #在索引为1,3的区间查找E的字符串
print(a3)
a4 = a.index('a')      #查找a
print(a4)
a5 = a.index('cd')     #查找cd
print(a5)

  运行结果:

D:\常用软件\Python3.7\python文件\python.exe D:/学习资料/项目/练习/lianxi.py
Traceback (most recent call last):
  File "D:/学习资料/项目/练习/lianxi.py", line 18, in <module>
0
    a3 = a.index('E',1,3)  #在索引为1,3的区间查找E的字符串
2
ValueError: substring not found

进程已结束,退出代码1
Raises ValueError when the substring is not found. #当没有找到的时候,直接返回错误进行报错。
这和运行结果中的是一样的,当没找到的时候直接就报错了,这是和find方法最大的不同。别的使用都是和find一样的。
find和indx的区别:

find和index的区别最大的就是没有查找到字符的时候返回的值不同。find返回的是-1而index直接报错。所以一般在编程中我们都是使用find而不是index,为了减少不必要的报错。

  字符串的大小写反转(swapcase):

    代码演示:

'''
def swapcase(self, *args, **kwargs): # real signature unknown
        """ Convert uppercase characters to lowercase and lowercase characters to uppercase. """
        pass
'''
a = "ABCDEFG"
a1 = a.swapcase()
print(a1)

   运行结果:

D:\常用软件\Python3.7\python文件\python.exe D:/学习资料/项目/练习/lianxi.py
abcdefg

   字符串切片(split):

   代码演示:

'''
 def split(self, *args, **kwargs): # real signature unknown
        """
        Return a list of the words in the string, using sep as the delimiter string.

          sep
            The delimiter according which to split the string.
            None (the default value) means split according to any whitespace,
            and discard empty strings from the result.
         maxsplit
            Maximum number of splits to do.
            -1 (the default value) means no limi t.
        """
        pass
'''
a = "ABC DE F G"
a1 = a.split(' ')
print(a1)

运行结果:

D:\常用软件\Python3.7\python文件\python.exe D:/学习资料/项目/练习/lianxi.py
['ABC', 'DE', 'F', 'G']

进程已结束,退出代码0

切片函数split的功能就是切割字符串,上面程序中使用空格进行切片,其实可以使用任意字符串中的符号进行切片,包括字符串中的字符,但是切片的时候,切片的标准回自动消失。如下面代码所示:

  代码演示:

a = "ABCDEFG"
a1 = a.split('D')
print(a1)

  运行结果: 

D:\常用软件\Python3.7\python文件\python.exe D:/学习资料/项目/练习/lianxi.py
['ABC', 'EFG']

 这就是切片的功能

居中空白填写(center):

代码演示:

def center(self, *args, **kwargs): # real signature unknown
"""
Return a centered string of length width.

Padding is done using the specified fill character (default is a space).
"""
pass
'''
a = "ABCDEFG"
a1 = a.center(20,'#')

a = "ABCDEFG"
a1 = a.center(20,'#')
a2 = a.center(20,' ')
a3 = a.center(20,'*')
print(a1)
print(a2)
print(a3)
 

代码解析:center(20,'#') 前面一个20表示总的字符长度为20个,后面的引号括起来的表示进行填的符号,可以是任意的符号。代码中展示了#,空格,星号等多种格式。

运行结果:

D:\常用软件\Python3.7\python文件\python.exe D:/学习资料/项目/练习/lianxi.py
######ABCDEFG#######
      ABCDEFG      
******ABCDEFG*******
进程已结束,退出代码0

这个center函数还是比较简单的

默认删除前后空格(strip):

代码演示:

'''
def strip(self, *args, **kwargs): # real signature unknown
"""
Return a copy of the string with leading and trailing whitespace remove.

If chars is given and not None, remove characters in chars instead.
"""
pass
'''
a = " ABCDEFG "
b = "****ACDEFG***"
c = "###ABCDEFG###"
a1 = a.strip()
b1 = a.strip('*')
c1 = a.strip()
print(a1)
print(b1)
print(c1)
  

代码解析:变量a中字符串前面是空格,变量b中字符串前面是星号,变量c中字符串中前面是#号 ,a1和c1是默认删除字符串的前面的符号位,并不保留符号位的占位。b1是删除前面的占位符的同时还保留这占位。

运行结果:

1 D:\常用软件\Python3.7\python文件\python.exe D:/学习资料/项目/练习/lianxi.py
2 ABCDEFG
3    ABCDEFG    
4 ABCDEFG
5 
6 进程已结束,退出代码0

删除空位字符串的时候需要注意strip()函数中是否传有参数

替换字符(replace):

代码演示:

'''
 def replace(self, *args, **kwargs): # real signature unknown
        """
        Return a copy with all occurrences of substring old replaced by new.

          count
            Maximum number of occurrences to replace.
            -1 (the default value) means replace all occurrences.

        If the optional argument count is given, only the first count occurrences are
        replaced.
        """
        pass
'''
a = 'huaohuaoahuaohuao'
a1 = a.replace('hu','ao') #没有指定的替换哪一个的时候,直接全部进行替换。
a2 = a.replace('hu','ao',3) #将前三个hu替换成为ao,后面的保持不动。
a3 = a.replace('hu','ao',1) #将前一个hu替换成为ao,后面的保持不动。
a4 = a.replace('hu','ao',0) #将前0个hu替换成为ao,后面的保持不动。
a5 = a.replace('hu','ao',-1) #-1表示默认,也就是默认全部替换的意思
a6 = a.replace('hu','ao',-5) # 在这里小于0的同一会当成负的,所以也就是直接全部替换。

print(a1)
print(a2)
print(a3)
print(a4)
print(a5)
print(a6)

运行结果:

1 D:\常用软件\Python3.7\python文件\python.exe D:/学习资料/项目/练习/lianxi.py
2 aoaoaoaoaaoaoaoao
3 aoaoaoaoaaoaohuao
4 aoaohuaoahuaohuao
5 huaohuaoahuaohuao
6 aoaoaoaoaaoaoaoao
7 aoaoaoaoaaoaoaoao
8 
9 进程已结束,退出代码0

在这个替换函数中,没有指明替换几个的前提下是会直接全部进行替换的。当指明替换的个数是负数时会直接认为成为默认的进行全部替换。正数则按照个数进行替换。

判断字符的长度(len):

代码演示:

1 '''
2  def len(*args, **kwargs): # real signature unknown
3     """ Return the number of items in a container. """
4     pass
5 
6 '''
7 a = 'huaohuaoahuaohuao'
8 a1 = len(a)
9 print(a1)

运行结果:

D:\常用软件\Python3.7\python文件\python.exe D:/学习资料/项目/练习/lianxi.py
17

进程已结束,退出代码0

len()函数是直接计算字符串长度的,使用也是很简单的。

字符串的计数(count):

代码演示:

 1 '''
 2  def count(self, sub, start=None, end=None): # real signature unknown; restored from __doc__
 3         """
 4         S.count(sub[, start[, end]]) -> int
 5 
 6         Return the number of non-overlapping occurrences of substring sub in
 7         string S[start:end].  Optional arguments start and end are
 8         interpreted as in slice notation.
 9         """
10         return 0
11 '''
12 a = 'huaohuaoahuaohuao'
13 a1 = a.count('hu',0,9)  # def count(self, sub, start=None, end=None): sub表示计数的字符串。start,end表示计数的范围
14 a2 = a.count('hu')      #没有指明范围的就是直接在全局范围类进行查找。 
15 print(a1)
16 print(a2)

运行结果:

D:\常用软件\Python3.7\python文件\python.exe D:/学习资料/项目/练习/lianxi.py
2
4

count()计数函数就是查找字符串里面,这样的字符有多少个。还是比较简单的一个函数。

字符串大小写的操作(upper(),lower(),capitalize()):

字符串全大写(upper()):

代码演示:

'''
def upper(self, *args, **kwargs): # real signature unknown
        """ Return a copy of the string converted to uppercase. """
        pass
'''
a = 'huaohuaoahuaohuao'
a1 = a.upper()
print(a1)

运行结果:

D:\常用软件\Python3.7\python文件\python.exe D:/学习资料/项目/练习/lianxi.py
HUAOHUAOAHUAOHUAO

进程已结束,退出代码0

这个方法没有什么难得,解释得也是一句话,直接返回该字符的大写形式。

字符串全小写(lower()):

代码演示; 

1 '''
2 def lower(self, *args, **kwargs): # real signature unknown
3         """ Return a copy of the string converted to lowercase. """
4         pass
5 '''
6 a = 'huaohuaoahuaohuao'
7 a1 = a.lower()
8 print(a1)

运行结果:

1 D:\常用软件\Python3.7\python文件\python.exe D:/学习资料/项目/练习/lianxi.py
2 huaohuaoahuaohuao

字符串首字母大写(capitalize()):

代码演示:

 1 '''
 2 def capitalize(self, *args, **kwargs): # real signature unknown
 3         """
 4         Return a capitalized version of the string.
 5         
 6         More specifically, make the first character have upper case and the rest lower
 7         case.
 8         """
 9         pass
10 '''
11 a = 'huaohuaoahuaohuao'
12 a1 = a.capitalize()
13 print(a1)

运行结果:

:\常用软件\Python3.7\python文件\python.exe D:/学习资料/项目/练习/lianxi.py
Huaohuaoahuaohuao

原文地址:https://www.cnblogs.com/huao990928/p/11594281.html