第二节 基本数据类型的一些笔记

Posted chency2018

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了第二节 基本数据类型的一些笔记相关的知识,希望对你有一定的参考价值。

写在最前面http://www.runoob.com/python3/python3-string.html,因为这个比较系统讲解,自学跟着讲师走的时候,顺便看一下详细的书籍可以更好掌握。以下内容为个人笔记。

今天通过PyCham 新建一个.py的新文件输入 str,然后按住Ctrl鼠标点击str,会跳出builtins.py,出现相应的class str(object)里面有详细介绍相关的使用内容,

截取一小部分内容如下:

lass str(object):
    """
    str(object=‘‘) -> str
    str(bytes_or_buffer[, encoding[, errors]]) -> str
    
    Create a new string object from the given object. If encoding or
    errors is specified, then the object must expose a data buffer
    that will be decoded using the given encoding and error handler.
    Otherwise, returns the result of object.__str__() (if defined)
    or repr(object).
    encoding defaults to sys.getdefaultencoding().
    errors defaults to ‘strict‘.
    """
    def capitalize(self, *args, **kwargs): # real signature unknown
        """
        Return a capitalized version of the string.
        
        More specifically, make the first character have upper case and the rest lower
        case.
        """
        pass

    def casefold(self, *args, **kwargs): # real signature unknown
        """ Return a version of the string suitable for caseless comparisons. """
        pass

    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

    def count(self, sub, start=None, end=None): # real signature unknown; restored from __doc__
        """
        S.count(sub[, start[, end]]) -> int
        
        Return the number of non-overlapping occurrences of substring sub in
        string S[start:end].  Optional arguments start and end are
        interpreted as in slice notation.
        """
        return 0

    def encode(self, *args, **kwargs): # real signature unknown
        """
        Encode the string using the codec registered for encoding.
        
          encoding
            The encoding in which to encode the string.
          errors
            The error handling scheme to use for encoding errors.
            The default is ‘strict‘ meaning that encoding errors raise a
            UnicodeEncodeError.  Other possible values are ‘ignore‘, ‘replace‘ and
            ‘xmlcharrefreplace‘ as well as any other name registered with
            codecs.register_error that can handle UnicodeEncodeErrors.
        """
        pass

    def endswith(self, suffix, start=None, end=None): # real signature unknown; restored from __doc__
        """
        S.endswith(suffix[, start[, end]]) -> bool
        
        Return True if S ends with the specified suffix, False otherwise.
        With optional start, test S beginning at that position.
        With optional end, stop comparing S at that position.
        suffix can also be a tuple of strings to try.
        """
        return False

    def expandtabs(self, *args, **kwargs): # real signature unknown
        """
        Return a copy where all tab characters are expanded using spaces.
        
        If tabsize is not given, a tab size of 8 characters is assumed.
        """
        pass

    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

    def format(self, *args, **kwargs): # known special case of str.format
        """
        S.format(*args, **kwargs) -> str
        
        Return a formatted version of S, using substitutions from args and kwargs.
        The substitutions are identified by braces (‘{‘ and ‘}‘).
        """
        pass

    def format_map(self, mapping): # real signature unknown; restored from __doc__
        """
        S.format_map(mapping) -> str
        
        Return a formatted version of S, using substitutions from mapping.
        The substitutions are identified by braces (‘{‘ and ‘}‘).
        """
        return ""

    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.
        """
        return 0

    def isalnum(self, *args, **kwargs): # real signature unknown
        """
        Return True if the string is an alpha-numeric string, False otherwise.
        
        A string is alpha-numeric if all characters in the string are alpha-numeric and
        there is at least one character in the string.
        """
        pass

    def isalpha(self, *args, **kwargs): # real signature unknown
        """
        Return True if the string is an alphabetic string, False otherwise.
        
        A string is alphabetic if all characters in the string are alphabetic and there
        is at least one character in the string.
        """
        pass

    def isascii(self, *args, **kwargs): # real signature unknown
        """
        Return True if all characters in the string are ASCII, False otherwise.
        
        ASCII characters have code points in the range U+0000-U+007F.
        Empty string is ASCII too.
        """
        pass

    def isdecimal(self, *args, **kwargs): # real signature unknown
        """
        Return True if the string is a decimal string, False otherwise.
        
        A string is a decimal string if all characters in the string are decimal and
        there is at least one character in the string.
        """
        pass

    def isdigit(self, *args, **kwargs): # real signature unknown
        """
        Return True if the string is a digit string, False otherwise.
        
        A string is a digit string if all characters in the string are digits and there
        is at least one character in the string.
        """
        pass

    def isidentifier(self, *args, **kwargs): # real signature unknown
        """
        Return True if the string is a valid Python identifier, False otherwise.
        
        Use keyword.iskeyword() to test for reserved identifiers such as "def" and
        "class".
        """
        pass

    

  看到满满的英文注释,所以学好英语是很有必要的,个人最近看的KK音标的讲师谢孟媛感觉讲的蛮好的,有种相见恨晚感觉。如果以前学习英语的入门能看到这个,整个人生将改变很大呀!至少英语再也不是中国式英语了,虽然谢孟媛老师是台湾的音标和国际音标有一些区别,但是对于我这种需要重铸发音来说是刚好的,反正发音没问题,考试会填就行,语法区别只是一些小的部分,问题重点在于学起来比较轻松。

  话不多说,接着写笔记。

# -*- coding: utf-8 -*-
# 首字母大写
test = python
v = test.capitalize()
print(v)

# 2 所有变小写,casefold更牛逼,很多未知的对相应变小写
test = SHLweSHGOSIDwew
v1 = test.casefold()
print(v1)
v2 = test.lower()
print(v2)

# 3 设置宽度,并将内容居中
test = python
#20 代指总长度,* 用来填充空白的,如果输入的内容大于20个字符就不需要填充,
#当然可以可以不输入直接v = test.center(20),这样就将内容在20个字符中居中
# 另外只能输入一个字符来填充空白不能如:v = test.center(20,‘*@‘)等其他组合字符
v = test.center(20,*)
print(v)

test = python
v = test.ljust(20,*)#ljust()中l代表着test = ‘python‘中python来占据右边的字符位,不满20字符的情况下在左边补到20个字符
print(v)

test = python
v = test.rjust(20,*)#rjust()中r代表着test = ‘python‘中python来占据右边的字符位,不满20字符的情况下在左边补到20个字符
print(v)

test = python
v = test.zfill(20) #zfill()是test = ‘python‘中python来占据右边的字符位,不满20字符的情况下在左边补到20个字符
print(v)
# 4 在字符串中寻找子序列出现的次数
test = python
v = test.count(tn) #输入的计数字符如果是多个的,需要和原文字符顺序一致,不然搜索到的个数为0
print(v)

test = python
#这里要注意一点搜索范围是[5,16]的字符里计数‘on‘这个字符串,
# 但是计数是从0开始,所以这里的字符串中的第5位开始算起。
v = test.count(on,4,16)
print(v)

# 5以什么开始和以什么结尾
test = python
v1 = test.startswith(py)
v2 = test.endswith(on)
print(v1)  #这里输出的结果是布尔值True或者False,
print(v2)

结果:

C:\Users\Administrator\PycharmProjects\python_s3\venv\Scripts\python.exe C:/Users/Administrator/PycharmProjects/python_s3/day_10/day11.py
Python
shlweshgosidwew
shlweshgosidwew
*******python*******
python**************
**************python
00000000000000python76        
0
1
True
True

Process finished with exit code 0
# 从开始往后找,找到第一个之后,获取其位置统计个数
# > 或 >=
test = "alexalex"
v1 = test.find(1ex) # 未找到 -1
v2 = test.find(ex)
print(v1)
print(v2)

# index找不到的时候会报错 一般使用find()来查找 可忽略
# test = "alexalex"
# v = test.index(‘8‘)
# print(v)


# 格式化,将一个字符串中的占位符替换为指定的值
test = i am {name}, age {a}
print(test)
v = test.format(name=alex,a=19)
print(v)
# 类似效果如下
print ("我叫 %s 今年 %d 岁!" % (小明, 10))

test = i am {0}, age {1}
print(test)
v = test.format(alex,19)
print(v)

# 格式化,传入的值 {"name": ‘alex‘, "a": 19}
test = i am {name}, age {a}
v1 = test.format(name=df,a=10)
v2 = test.format_map({"name": alex, "a": 19})#这里需要用大括号来将里面的字符串进行更改

# 字符串中是否只包含 字母和数字
test = "123"
v = test.isalnum()
print(v)

结果:

C:\Users\Administrator\PycharmProjects\python_s3\venv\Scripts\python.exe "C:/Users/Administrator/Desktop/python全栈3期-课件与源码/python全栈3期-课件与源码/day10源码/python全栈s3  day10课上所有/day10/s1.py"
-1
2
i am {name}, age {a}
i am alex, age 19
我叫 小明 今年 10 岁!
i am {0}, age {1}
i am alex, age 19
True

Process finished with exit code 0
# 12 是否是字母,汉字
test = "as2df"
v = test.isalpha()
print(v)

# 13 当前输入是否是数字
test = "" # 1,②
v1 = test.isdecimal() #识别十进制数
v2 = test.isdigit()  #识别十进制数和特殊数字如:1,②
v3 = test.isnumeric() #识别所以数字
print(v1,v2,v3)  #输出布尔值


# 14 是否存在不可显示的字符
# \t   制表符
# \n   换行
test = "oiuas\tdfkj"
v = test.isprintable() #不能够显示转义字符
print(v)

# 15 判断是否全部是空格
test = "    "
v = test.isspace()
print(test中需要加入空格才能判断为空,如果test=""为False:,v)
test = ""
v = test.isspace()
print(test中需要加入空格才能判断为空,如果test=""为False:,v)

# 16 判断是否是标题
test = "Return True if all cased characters in S are uppercase and there is"
v1 = test.istitle()#如果 string 是标题化的(见 title())则返回 True,否则返回 False
print(v1)
v2 = test.title()#转变成为标题,返回"标题化"的 string,就是说所有单词都是以大写开始,其余字母均为小写
print(v2)
v3 = v2.istitle()#如果 string 是标题化的(见 title())则返回 True,否则返回 False
print(v3)

# 17 ***** 将字符串中的每一个元素按照指定分隔符进行拼接
test = "你是风儿我是沙"
print(test)
v = "_".join(test)
print(v)  #返回通过指定字符连接序列中元素后生成的新字符串

# 18 判断是否全部是大小写 和 转换为大小写
test = "Alex"
v1 = test.islower()#判断是否全部是小写
v2 = test.lower() #转换为小写
print(v1, v2)

# v1 = test.isupper()#判断是否全部是大写
# v2 = test.upper()#转换为大写
# print(v1,v2)

# 19 移除指定字符串
# 有限最多匹配
test = "alwxa"
# 从右边开始找相同字符,比如‘alexaw‘就不会被删,因为从右边起有不在删除字符串里的字母自动停止删除
v = test.rstrip(9lexxexa)
print(v)

test = "alwxa"
v1 = test.lstrip(xa)#从左往右找相同字符删除,遇见不同自动停止
v2 = test.strip(xa)#查找所有字符中包含要删的元素进行删除
print(v1)
print(v2)
# 去除左右空白
# test.lstrip()
# test.rstrip()
# test.strip()

test = "  alwxa    "
v = test.lstrip("去除左空白:")# 去除左空白,这个无效
# v = test.rstrip()# 去除末尾空白
# v = test.strip()# 去除左右空白
print(v)
# print(test)
# 去除\t \n
# v = test.lstrip()
# v = test.rstrip()
# v = test.strip()
# print(v)

# 20 对应关系替换
test =  "aeiou"
test1 = "12345"

v = "asidufkasd;fiuadkf;adfkjalsdjf"
m = str.maketrans("aeiou", "12345")#对指定的字符串进行替换,其中的字符串个数一致一一对应
new_v = v.translate(m)
print(new_v)

# 21 分割为三部分
# test = "testasdsddfg"
# v = test.partition(‘s‘) #对首个s进行分割,保留分割字符
# print(v)
# v = test.rpartition(‘s‘)#从右往左对首个s进行分割
# print(v)

# 22 分割为指定个数
test = "testasdsddfg"
v = test.split(s,2) #分割的时候分割字符会丢失,2代表从左往右分割其中两个s
print(v)
test.rsplit()


# 23 分割,只能根据,true,false:是否保留换行
test = "asdfadfasdf\nasdfasdf\nadfasdf"
v = test.splitlines(True)
print(v)

#  24 以xxx开头,以xx结尾
test = "backend 1.1.1.1"
v = test.startswith(a)
print(v)
test = "backend 1.1.1.1"
v = test.endswith(a)
print(v)

# 25 大小写转换
test = "aLex"
v = test.swapcase()
print(v)

# 26 字母,数字,下划线 : 标识符 def  class
a = "def"
v = a.isidentifier()
print(v)


# 27 将指定字符串替换为指定字符串
test = "alexalexalex"
v = test.replace("ex",bbb)
print(v)
test = "alexalexalex"
v = test.replace("ex",bbb,2)
print(v)

需要熟记的有其中几种:join ,split,find ,strip,upper,lower,replace

test = "千里之行始于足下"
index = 0
while index < len(test):
    v = test[index]
    print(v)

    index += 1
print(=======)
# 如果有字符串在其中打印所有
for 足下 in test:
    print(足下)

test = "千里之行始于足下"

for item in test:
    print(item) #item()方法遍历字典的例子
    break  #输出第一个

for item in test:
    continue  #跳不过continue所有没有打印内容
    print(item)

# 二、索引,下标,获取字符串中的某一个字符
v = test[3] #index算法是算字符需要从0数到3,也就是在第四位
print(v)

# 三、切片
v = test[0:-1] # 在第一个和最后一个字符之前
print(v)

# 四、获取长度
# Python3: len获取当前字符串中由几个字符组成
v = len(test) 
print(v)

结果

千
里
之
行
始
于
足
下
=======
千
里
之
行
始
于
足
下
千
行
千里之行始于足
8
# 五、获取连续或不连续的数字,
# Python2中直接创建在内容中
# python3中只有for循环时,才一个一个创建
# r1 = range(10)
# r2 = range(1,10)
# r3 = range(1,10,2)
# # 帮助创建连续的数字,通过设置步长来指定不连续
# v = range(0, 101, 5)#[0,100]每5个取一个数字

# for item in v:
#     print(item)

##### 练习题:根据用户输入的值,输出每一个字符以及当前字符所在的索引位置 #####
# test = input(">>>")
# for item in test:
#     print(item)

# 将文字 对应的索引打印出来:
test = input("请输入:")#以输入qwe为例
print(test)   # test = qwe   test[0]   test[1]
l = len(test) # qwe长度为l = 3
print(l)

r = range(0,l) # range中的数和l中的字符串一一对应0,3
for item in r:
    print(item, test[item]) # 0 q,1 w,2 e
#简化版本
test = input(">>>")
for item in range(0, len(test)):
    print(item, test[item])

###################### 1个深灰魔法 ######################
# 字符串一旦创建,不可修改
# 一旦修改或者拼接,都会造成重新生成字符串
name = "yezhiqiu"
age = "18"

info = name + age
print(info)

 

以上是关于第二节 基本数据类型的一些笔记的主要内容,如果未能解决你的问题,请参考以下文章

手写数字识别——基于全连接层和MNIST数据集

:Python的基本数据类型-第二节:Python中表示“有序”(序列)的数据类型

《斯坦福大学:编程范式》第二节:基本数据类型在内存中的二进制表达

Clickhouse系列-第二节-基本原理

第二十二节 面向对象 简单小结类与对象

斯坦福大学数据可视化课程学习笔记:第二节 从数据到图像