磨人的小妖精们啊!终于可以归置下自己的大脑啦,在这里我要把——整型,长整型,浮点型,字符串,列表,元组,字典,集合,这几个知识点特别多的东西,统一的捯饬捯饬,不然一直脑袋里面乱乱的。

对于Python,一切事物都是对象,对象基于类创建

所以,以下这些值都是对象: "wupeiqi"、38、['北京', '上海', '深圳'],并且是根据不同的类生成的对象。

官方的解释是这样的:对象是对客观事物的抽象,类是对对象的抽象。

  因此str是类,int是类,dict、list、tuple等等都是类,但是str却不能直接使用,因为它是抽象的表示了字符串这一类事物,并不能满足表示某个特定字符串的需求,我们必须要str1 = ''初始化一个对象,这时的str1具有str的属性,可以使用str中的方法。

  类为我们创建对象,提供功能,在python中,一切事物都是对象!(瞧,谁还敢嫌弃我们程序员没有对象,我们可以new一个呀!)

在这里介绍些类、对象、方法的查看方式:

1 >>> str1='zhenghao'
2 >>> type(str1)
3 <type 'str'>
4 >>>

查看类的所有方法:dir(类名),就打印出了所有的类方法。

>>> dir(str)
['__add__', '__class__', '__contains__', '__delattr__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__getslice__', '__gt__', '__hash__', '__init__', '__le__', '__len__', '__lt__', '__mod__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmod__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '_formatter_field_name_split', '_formatter_parser', 'capitalize', 'center', 'count', 'decode', 'encode', 'endswith', 'expandtabs', 'find', 'format', 'index', 'isalnum', 'isalpha', 'isdigit', 'islower', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'partition', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill']

那么问题来了,方法名为什么有的两边带着下划线,有的没有呢?那是python用来标识私有方法、非私有方法哒,带下划线的标识私有方法,他们通常拥有不止一种调用方法。如下,我定义了两个字符串,__add__的+的效果是相同的。这里有一个内置方法很特殊:__init__,它是类中的构造方法,会在调用其所在类的时候自动执行。

1 >>> str1='zhenghao'
2 >>> str2='love xiaokai'
3 >>> str1.__add__(str2)
4 'zhenghaolove xiaokai'
5 >>> str1+str2
6 'zhenghaolove xiaokai'
7 >>>

在python中,还有一个“help(类名)”方法:可以查看类的详细功能;“help(类名.功能名)”:查看类中某功能的详细情况

 

一、整数


整数是不可变的,不可迭代的

1.全部的方法

1 >>> dir(int)
2 ['__abs__', '__add__', '__and__', '__clas s__', '__cmp__', '__coerce__', '__delattr__', '__div__', '__divmod__', '__doc__', '__float__', '__floordiv__', '__format__', '__getattribute__', '__getnewargs__', '__hash__', '__hex__', '__index__', '__init__', '__int__', '__invert__', '__long__', '__lshift__', '__mod__', '__mul__', '__neg__', '__new__', '__nonzero__', '__oct__', '__or__', '__pos__', '__pow__', '__radd__', '__rand__', '__rdiv__', '__rdivmod__', '__reduce__', '__reduce_ex__', '__repr__', '__rfloordiv__', '__rlshift__', '__rmod__', '__rmul__', '__ror__', '__rpow__', '__rrshift__', '__rshift__', '__rsub__', '__rtruediv__', '__rxor__', '__setattr__', '__sizeof__', '__str__', '__sub__', '__subclasshook__', '__truediv__', '__trunc__', '__xor__', 'bit_length', 'conjugate', 'denominator', 'imag', 'numerator', 'real'] 

每一个整数都具备如下功能:

 class int(object):
"""
int(x=0) -> int or long
int(x, base=10) -> int or long Convert a number or string to an integer, or return 0 if no arguments
are given. If x is floating point, the conversion truncates towards zero.
If x is outside the integer range, the function returns a long instead. If x is not a number or if base is given, then x must be a string or
Unicode object representing an integer literal in the given base. The
literal can be preceded by '+' or '-' and be surrounded by whitespace.
The base defaults to 10. Valid bases are 0 and 2-36. Base 0 means to
interpret the base from the string as an integer literal.
>>> int('0b100', base=0)
4
"""
def bit_length(self): # real signature unknown; restored from __doc__
"""返回表示该数字时所用的最小位数
int.bit_length() -> int Number of bits necessary to represent self in binary.
>>> bin(37)
'0b100101'
>>> (37).bit_length()
6
"""
return 0 def conjugate(self, *args, **kwargs): # real signature unknown
"""返回一个复数的共轭复数
Returns self, the complex conjugate of any int. """
pass def __abs__(self): # real signature unknown; restored from __doc__
""" 返回绝对值
x.__abs__() <==> abs(x) """
pass def __add__(self, y): # real signature unknown; restored from __doc__
""" 返回两个数的和
x.__add__(y) <==> x+y """
pass def __and__(self, y): # real signature unknown; restored from __doc__
""" 返回两个数按位与的结果
x.__and__(y) <==> x&y """
pass def __cmp__(self, y): # real signature unknown; restored from __doc__
"""返回两个数比较的结果,参数从左至右(a,b),a>b返回1,a<b返回-1,a=b返回0
x.__cmp__(y) <==> cmp(x,y) """
pass def __coerce__(self, y): # real signature unknown; restored from __doc__
"""a.__coerce__(b),强制返回一个元组(a,b)
x.__coerce__(y) <==> coerce(x, y) """
pass def __divmod__(self, y): # real signature unknown; restored from __doc__
""" 相除,得到商和余数组成的元组
x.__divmod__(y) <==> divmod(x, y) """
pass def __div__(self, y): # real signature unknown; restored from __doc__
"""返回两数相除的商
x.__div__(y) <==> x/y """
pass def __float__(self): # real signature unknown; restored from __doc__
"""将数据类型强制转换为float
x.__float__() <==> float(x) """
pass def __floordiv__(self, y): # real signature unknown; restored from __doc__
""" 不保留小数点后的小数除法,也可以用‘//’来表示:a//b,我们亲切地称之为“地板除”!!!
x.__floordiv__(y) <==> x//y """
pass def __format__(self, *args, **kwargs): # real signature unknown
""" 格式化"""
pass def __getattribute__(self, name): # real signature unknown; restored from __doc__
"""无条件被调用,通过实例访问属性
x.__getattribute__('name') <==> x.name """
pass def __getnewargs__(self, *args, **kwargs): # real signature unknown
""" 内部调用 __new__方法或创建对象时传入参数使用 """
pass def __hash__(self): # real signature unknown; restored from __doc__
""" 如果对象object为哈希表类型,返回对象object的哈希值。哈希值为整数。在字典查找中,哈希值用于快速比较字典的键。两个数值如果相等,则哈希值也相等
x.__hash__() <==> hash(x) """
pass def __hex__(self): # real signature unknown; restored from __doc__
""" 返回当前数的 十六进制 表示
x.__hex__() <==> hex(x) """
pass def __index__(self): # real signature unknown; restored from __doc__
""" 用于切片,对数字无意义
x[y:z] <==> x[y.__index__():z.__index__()] """
pass def __init__(self, x, base=10): # known special case of int.__init__
"""构造函数
int(x=0) -> int or long
int(x, base=10) -> int or long Convert a number or string to an integer, or return 0 if no arguments
are given. If x is floating point, the conversion truncates towards zero.
If x is outside the integer range, the function returns a long instead. If x is not a number or if base is given, then x must be a string or
Unicode object representing an integer literal in the given base. The
literal can be preceded by '+' or '-' and be surrounded by whitespace.
The base defaults to 10. Valid bases are 0 and 2-36. Base 0 means to
interpret the base from the string as an integer literal.
>>> int('0b100', base=0)
4
# (copied from class doc)
"""
pass def __int__(self): # real signature unknown; restored from __doc__
""" 转换为整数
x.__int__() <==> int(x) """
pass def __invert__(self): # real signature unknown; restored from __doc__
"""按位求反
x.__invert__() <==> ~x """
pass def __long__(self): # real signature unknown; restored from __doc__
"""转换为长整数
x.__long__() <==> long(x) """
pass def __lshift__(self, y): # real signature unknown; restored from __doc__
""" 左移,相对二进制的操作
x.__lshift__(y) <==> x<<y """
pass def __mod__(self, y): # real signature unknown; restored from __doc__
""" 取余
x.__mod__(y) <==> x%y """
pass def __mul__(self, y): # real signature unknown; restored from __doc__
""" 返回两数相乘的积
x.__mul__(y) <==> x*y """
pass def __neg__(self): # real signature unknown; restored from __doc__
""" 返回一个数的负数,个人觉得和相反数没差
x.__neg__() <==> -x """
pass @staticmethod # known case of __new__
def __new__(S, *more): # real signature unknown; restored from __doc__
""" 创建一个int类的新对象
T.__new__(S, ...) -> a new object with type S, a subtype of T """
pass def __nonzero__(self): # real signature unknown; restored from __doc__
""" 判断一个数是不是0
x.__nonzero__() <==> x != 0 """
pass def __oct__(self): # real signature unknown; restored from __doc__
""" 返回该值的 八进制 表示
x.__oct__() <==> oct(x) """
pass def __or__(self, y): # real signature unknown; restored from __doc__
""" 位运算,或,针对二进制数
x.__or__(y) <==> x|y """
pass def __pos__(self): # real signature unknown; restored from __doc__
""" 并没什么卵用,说是a.__pos__(),会返回一个+a,但是不管输入整数还是负数,返回值都是他本身,感觉歪果仁真有幽默感
x.__pos__() <==> +x """
pass def __pow__(self, y, z=None): # real signature unknown; restored from __doc__
""" 幂,次方
x.__pow__(y[, z]) <==> pow(x, y[, z]) """
pass def __radd__(self, y): # real signature unknown; restored from __doc__
"""x.__radd__(y) <==> y+x """
pass def __rand__(self, y): # real signature unknown; restored from __doc__
"""x.__rand__(y) <==> y&x """
pass def __rdivmod__(self, y): # real signature unknown; restored from __doc__
""" x.__rdivmod__(y) <==> divmod(y, x) """
pass def __rdiv__(self, y): # real signature unknown; restored from __doc__
""" x.__rdiv__(y) <==> y/x """
pass def __repr__(self): # real signature unknown; restored from __doc__
""" 转化为解释器可读取的形式
x.__repr__() <==> repr(x) """
pass def __rfloordiv__(self, y): # real signature unknown; restored from __doc__
"""
x.__rfloordiv__(y) <==> y//x """
pass def __rlshift__(self, y): # real signature unknown; restored from __doc__
""" x.__rlshift__(y) <==> y<<x """
pass def __rmod__(self, y): # real signature unknown; restored from __doc__
""" x.__rmod__(y) <==> y%x """
pass def __rmul__(self, y): # real signature unknown; restored from __doc__
""" x.__rmul__(y) <==> y*x """
pass def __ror__(self, y): # real signature unknown; restored from __doc__
""" x.__ror__(y) <==> y|x """
pass def __rpow__(self, x, z=None): # real signature unknown; restored from __doc__
""" y.__rpow__(x[, z]) <==> pow(x, y[, z]) """
pass def __rrshift__(self, y): # real signature unknown; restored from __doc__
""" x.__rrshift__(y) <==> y>>x """
pass def __rshift__(self, y): # real signature unknown; restored from __doc__
""" x.__rshift__(y) <==> x>>y """
pass def __rsub__(self, y): # real signature unknown; restored from __doc__
""" x.__rsub__(y) <==> y-x """
pass def __rtruediv__(self, y): # real signature unknown; restored from __doc__
""" x.__rtruediv__(y) <==> y/x """
pass def __rxor__(self, y): # real signature unknown; restored from __doc__
""" x.__rxor__(y) <==> y^x """
pass def __str__(self): # real signature unknown; restored from __doc__
""" 转换为人阅读的形式,如果没有适于人阅读的解释形式的话,则返回解释器课阅读的形式
x.__str__() <==> str(x) """
pass def __sub__(self, y): # real signature unknown; restored from __doc__
""" 返回两数相减的差
x.__sub__(y) <==> x-y """
pass def __truediv__(self, y): # real signature unknown; restored from __doc__
"""返回两数相除的商,这里的除是精确的除法,不会省略小数点后的值
x.__truediv__(y) <==> x/y """
pass def __trunc__(self, *args, **kwargs): # real signature unknown
"""返回数值被截取为整形的值,在整形中无意义
Truncating an Integral returns itself. """
pass def __xor__(self, y): # real signature unknown; restored from __doc__
""" 按位异或
x.__xor__(y) <==> x^y """
pass denominator = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
""" 分母 = 1 """
"""the denominator of a rational number in lowest terms""" imag = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
""" 虚数,无意义 """
"""the imaginary part of a complex number""" numerator = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
""" 分子 = 数字大小 """
"""the numerator of a rational number in lowest terms""" real = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
""" 实数,无意义 """
"""the real part of a complex number""" int Code

help(int)

我已经在源码中加入了注释,原谅我后面很多函数没有加注释都,因为那些前面在前面已近出现过了,只是在前面多了一个'r'的,比如and,变成了rand,在这里统一总结,就是参数的顺序从右到左反过来了。比如原本的a.__div__(b)是a/b,但是a.__rdiv__(b)的表示的就是b/a,对!就是这么坑爹!

2.常用方法

在int类中,比较普通的就是+,-,*,/,%,位运算,进制间以及数据类型间的转换。下面对于比较特别但是常用的方法再进行一下记录:

(1) __cmp__:比较两个数的大小

1 >>> a = 12
2 >>> b = 15
3 >>> cmp(a,b) #比较两个参数的值,如果第一个参数小于第二个参数,返回-1
4 -1
5 >>> cmp(b,a) #比较两个参数的值,如果第一个参数大于第二个参数,返回1
6 1
7 >>> c = 12
8 >>> a.__cmp__(c) #比较两个参数的值,如果第一个参数等于第二个参数,返回0
9 0 #cmp方法也有两种调用方式

(2)__neg__/__abs__:取相反数/取绝对值

 1 >>> a = -12
2 >>> b = 21
3 >>> a.__neg__() #求相反数
4 12
5 >>> b.__neg__()
6 -21
7 >>> a.__abs__() #求绝对值
8 12
9 >>> b.__abs__()
10 21

(3)__coerce__:强制返回一个元组(好吧,我承认这个并不常用,就是和divmod比较看看)

(4)__divmod__:返回两个数相除的商和余数组成的元组(商,余数)                 应用:显示数据分页

1 >>> a = 102
2 >>> b = 10
3 >>> a.__divmod__(b)
4 (10, 2)
5 >>> a.__coerce__(b)
6 (102, 10)

(5)__floordiv__:不保留小数点后的小数除法,在这儿把所有的除法都整理了,然而我并没发现__div__和__floordiv__的区别啊~~~      

 1 >>> a = 13
2 >>> b = 2
3 >>> a.__div__(b)
4 6
5 >>> a.__truediv__(b)
6 6.5
7 >>> a.__floordiv__(b)
8 6
9 >>> a/b
10 6
11 >>> a//b
12 6

(6)__repr__/__str__:转化为解释器可读取的形式/转换为人阅读的形式

二、长整型

可能如:2147483649、9223372036854775807

1 >>> dir(long)
2 ['__abs__', '__add__', '__and__', '__class__', '__cmp__', '__coerce__', '__delattr__', '__div__', '__divmod__', '__doc__', '__float__', '__floordiv__', '__format__', '__getattribute__', '__getnewargs__', '__hash__', '__hex__', '__index__', '__init__', '__int__', '__invert__', '__long__', '__lshift__', '__mod__', '__mul__', '__neg__', '__new__', '__nonzero__', '__oct__', '__or__', '__pos__', '__pow__', '__radd__', '__rand__', '__rdiv__', '__rdivmod__', '__reduce__', '__reduce_ex__', '__repr__', '__rfloordiv__', '__rlshift__', '__rmod__', '__rmul__', '__ror__', '__rpow__', '__rrshift__', '__rshift__', '__rsub__', '__rtruediv__', '__rxor__', '__setattr__', '__sizeof__', '__str__', '__sub__', '__subclasshook__', '__truediv__', '__trunc__', '__xor__', 'bit_length', 'conjugate', 'denominator', 'imag', 'numerator', 'real']

每个长整型都具备如下功能:

 long

长整形就是长长的整形。。。现在的操作系统大部分int类型的表示范围是2^32,而长整形就是2^64,在python里,不需要程序员手动的转换int和long的数据类型,当数值的大小超过了int的表示范围,python会自动将数据类型转换为long型,就是这么智能!!!既然long和int同表示整形,那么他们包含的方法也是差不多的,在这里就不再介绍了。

三、浮点型

如:3.14、2.88

1 >>> dir(float)
2 ['__abs__', '__add__', '__class__', '__coerce__', '__delattr__', '__div__', '__divmod__', '__doc__', '__eq__', '__float__', '__floordiv__', '__format__', '__ge__', '__getattribute__', '__getformat__', '__getnewargs__', '__gt__', '__hash__', '__init__', '__int__', '__le__', '__long__', '__lt__', '__mod__', '__mul__', '__ne__', '__neg__', '__new__', '__nonzero__', '__pos__', '__pow__', '__radd__', '__rdiv__', '__rdivmod__', '__reduce__', '__reduce_ex__', '__repr__', '__rfloordiv__', '__rmod__', '__rmul__', '__rpow__', '__rsub__', '__rtruediv__', '__setattr__', '__setformat__', '__sizeof__', '__str__', '__sub__', '__subclasshook__', '__truediv__', '__trunc__', 'as_integer_ratio', 'conjugate', 'fromhex', 'hex', 'imag', 'is_integer', 'real']

每个浮点型都具备如下功能:

 float

我们在创建对象的时候,python也会很聪明的识别出float类型,在计算的时候也是这样,不管表达式中有多少整形多少浮点型,只要存在浮点型,那么所有计算都按照浮点型计算,得出的结果也会是float类型。其余方法和整形并没有太大差别,在这里也不做详细总结了。

四、字符串


字符串是不可修改不可变的,有序的,不可迭代的,有索引和切片

1.字符串全部方法

如:'zhenghao'、‘xiaokai'

1 >>> dir(str)
2 ['__add__', '__class__', '__contains__', '__delattr__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__getslice__', '__gt__', '__hash__', '__init__', '__le__', '__len__', '__lt__', '__mod__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmod__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '_formatter_field_name_split', '_formatter_parser', 'capitalize', 'center', 'count', 'decode', 'encode', 'endswith', 'expandtabs', 'find', 'format', 'index', 'isalnum', 'isalpha', 'isdigit', 'islower', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'partition', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill']

每个字符串都具备如下功能:

 class str(basestring):
"""
str(object='') -> string Return a nice string representation of the object.
If the argument is a string, the return value is the same object.
"""
def capitalize(self):
""" 首字母变大写 """
"""
S.capitalize() -> string Return a copy of the string S with only its first character
capitalized.
"""
return "" def center(self, width, fillchar=None):
""" 内容居中,width:总长度;fillchar:空白处填充内容,默认无 """
"""
S.center(width[, fillchar]) -> string Return S centered in a string of length width. Padding is
done using the specified fill character (default is a space)
"""
return "" def count(self, sub, start=None, end=None):
""" 子序列个数 """
"""
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 decode(self, encoding=None, errors=None):
""" 解码 """
"""
S.decode([encoding[,errors]]) -> object Decodes S using the codec registered for encoding. encoding defaults
to the default encoding. errors may be given to set a different error
handling scheme. Default is 'strict' meaning that encoding errors raise
a UnicodeDecodeError. Other possible values are 'ignore' and 'replace'
as well as any other name registered with codecs.register_error that is
able to handle UnicodeDecodeErrors.
"""
return object() def encode(self, encoding=None, errors=None):
""" 编码,针对unicode """
"""
S.encode([encoding[,errors]]) -> object Encodes S using the codec registered for encoding. encoding defaults
to the default encoding. errors may be given to set a different error
handling scheme. 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 is able to handle UnicodeEncodeErrors.
"""
return object() def endswith(self, suffix, start=None, end=None):
""" 是否以 xxx 结束 """
"""
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, tabsize=None):
""" 将tab转换成空格,默认一个tab转换成8个空格 """
"""
S.expandtabs([tabsize]) -> string Return a copy of S where all tab characters are expanded using spaces.
If tabsize is not given, a tab size of 8 characters is assumed.
"""
return "" def find(self, sub, start=None, end=None):
""" 寻找子序列位置,如果没找到,则异常 """
"""
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(*args, **kwargs): # known special case of str.format
""" 字符串格式化,动态参数,将函数式编程时细说 """
"""
S.format(*args, **kwargs) -> string Return a formatted version of S, using substitutions from args and kwargs.
The substitutions are identified by braces ('{' and '}').
"""
pass def index(self, sub, start=None, end=None):
""" 子序列位置,如果没找到,则返回-1 """
S.index(sub [,start [,end]]) -> int Like S.find() but raise ValueError when the substring is not found.
"""
return 0 def isalnum(self):
""" 是否是字母和数字 """
"""
S.isalnum() -> bool Return True if all characters in S are alphanumeric
and there is at least one character in S, False otherwise.
"""
return False def isalpha(self):
""" 是否是字母 """
"""
S.isalpha() -> bool Return True if all characters in S are alphabetic
and there is at least one character in S, False otherwise.
"""
return False def isdigit(self):
""" 是否是数字 """
"""
S.isdigit() -> bool Return True if all characters in S are digits
and there is at least one character in S, False otherwise.
"""
return False def islower(self):
""" 是否小写 """
"""
S.islower() -> bool Return True if all cased characters in S are lowercase and there is
at least one cased character in S, False otherwise.
"""
return False def isspace(self):
"""是否空格
S.isspace() -> bool Return True if all characters in S are whitespace
and there is at least one character in S, False otherwise.
"""
return False def istitle(self):
"""是否标题
S.istitle() -> bool Return True if S is a titlecased string and there is at least one
character in S, i.e. uppercase characters may only follow uncased
characters and lowercase characters only cased ones. Return False
otherwise.
"""
return False def isupper(self):
"""是否大写
S.isupper() -> bool Return True if all cased characters in S are uppercase and there is
at least one cased character in S, False otherwise.
"""
return False def join(self, iterable):
""" 连接 """
"""
S.join(iterable) -> string Return a string which is the concatenation of the strings in the
iterable. The separator between elements is S.
"""
return "" def ljust(self, width, fillchar=None):
""" 内容左对齐,右侧填充 """
"""
S.ljust(width[, fillchar]) -> string Return S left-justified in a string of length width. Padding is
done using the specified fill character (default is a space).
"""
return "" def lower(self):
""" 变小写 """
"""
S.lower() -> string Return a copy of the string S converted to lowercase.
"""
return "" def lstrip(self, chars=None):
""" 移除左侧空白 """
"""
S.lstrip([chars]) -> string or unicode Return a copy of the string S with leading whitespace removed.
If chars is given and not None, remove characters in chars instead.
If chars is unicode, S will be converted to unicode before stripping
"""
return "" def partition(self, sep):
""" 分割,前,中,后三部分 """
"""
S.partition(sep) -> (head, sep, tail) Search for the separator sep in S, and return the part before it,
the separator itself, and the part after it. If the separator is not
found, return S and two empty strings.
"""
pass def replace(self, old, new, count=None):
""" 替换 """
"""
S.replace(old, new[, count]) -> string Return a copy of string S with all occurrences of substring
old replaced by new. If the optional argument count is
given, only the first count occurrences are replaced.
"""
return "" def rfind(self, sub, start=None, end=None):
"""
S.rfind(sub [,start [,end]]) -> int Return the highest 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 rindex(self, sub, start=None, end=None):
"""
S.rindex(sub [,start [,end]]) -> int Like S.rfind() but raise ValueError when the substring is not found.
"""
return 0 def rjust(self, width, fillchar=None):
"""
S.rjust(width[, fillchar]) -> string Return S right-justified in a string of length width. Padding is
done using the specified fill character (default is a space)
"""
return "" def rpartition(self, sep):
"""
S.rpartition(sep) -> (head, sep, tail) Search for the separator sep in S, starting at the end of S, and return
the part before it, the separator itself, and the part after it. If the
separator is not found, return two empty strings and S.
"""
pass def rsplit(self, sep=None, maxsplit=None):
"""
S.rsplit([sep [,maxsplit]]) -> list of strings Return a list of the words in the string S, using sep as the
delimiter string, starting at the end of the string and working
to the front. If maxsplit is given, at most maxsplit splits are
done. If sep is not specified or is None, any whitespace string
is a separator.
"""
return [] def rstrip(self, chars=None):
"""
S.rstrip([chars]) -> string or unicode Return a copy of the string S with trailing whitespace removed.
If chars is given and not None, remove characters in chars instead.
If chars is unicode, S will be converted to unicode before stripping
"""
return "" def split(self, sep=None, maxsplit=None):
""" 分割, maxsplit最多分割几次 """
"""
S.split([sep [,maxsplit]]) -> list of strings Return a list of the words in the string S, using sep as the
delimiter string. If maxsplit is given, at most maxsplit
splits are done. If sep is not specified or is None, any
whitespace string is a separator and empty strings are removed
from the result.
"""
return [] def splitlines(self, keepends=False):
""" 根据换行分割 """
"""
S.splitlines(keepends=False) -> list of strings Return a list of the lines in S, breaking at line boundaries.
Line breaks are not included in the resulting list unless keepends
is given and true.
"""
return [] def startswith(self, prefix, start=None, end=None):
""" 是否起始 """
"""
S.startswith(prefix[, start[, end]]) -> bool Return True if S starts with the specified prefix, False otherwise.
With optional start, test S beginning at that position.
With optional end, stop comparing S at that position.
prefix can also be a tuple of strings to try.
"""
return False def strip(self, chars=None):
""" 移除两段空白 """
"""
S.strip([chars]) -> string or unicode Return a copy of the string S with leading and trailing
whitespace removed.
If chars is given and not None, remove characters in chars instead.
If chars is unicode, S will be converted to unicode before stripping
"""
return "" def swapcase(self):
""" 大写变小写,小写变大写 """
"""
S.swapcase() -> string Return a copy of the string S with uppercase characters
converted to lowercase and vice versa.
"""
return "" def title(self):
"""
S.title() -> string Return a titlecased version of S, i.e. words start with uppercase
characters, all remaining cased characters have lowercase.
"""
return "" def translate(self, table, deletechars=None):
"""
转换,需要先做一个对应表,最后一个表示删除字符集合
intab = "aeiou"
outtab = ""
trantab = maketrans(intab, outtab)
str = "this is string example....wow!!!"
print str.translate(trantab, 'xm')
""" """
S.translate(table [,deletechars]) -> string Return a copy of the string S, where all characters occurring
in the optional argument deletechars are removed, and the
remaining characters have been mapped through the given
translation table, which must be a string of length 256 or None.
If the table argument is None, no translation is applied and
the operation simply removes the characters in deletechars.
"""
return "" def upper(self):
"""
S.upper() -> string Return a copy of the string S converted to uppercase.
"""
return "" def zfill(self, width):
"""方法返回指定长度的字符串,原字符串右对齐,前面填充0。"""
"""
S.zfill(width) -> string Pad a numeric string S with zeros on the left, to fill a field
of the specified width. The string S is never truncated.
"""
return "" def _formatter_field_name_split(self, *args, **kwargs): # real signature unknown
pass def _formatter_parser(self, *args, **kwargs): # real signature unknown
pass def __add__(self, y):
""" x.__add__(y) <==> x+y """
pass def __contains__(self, y):
""" x.__contains__(y) <==> y in x """
pass def __eq__(self, y):
""" x.__eq__(y) <==> x==y """
pass def __format__(self, format_spec):
"""
S.__format__(format_spec) -> string Return a formatted version of S as described by format_spec.
"""
return "" def __getattribute__(self, name):
""" x.__getattribute__('name') <==> x.name """
pass def __getitem__(self, y):
""" x.__getitem__(y) <==> x[y] """
pass def __getnewargs__(self, *args, **kwargs): # real signature unknown
pass def __getslice__(self, i, j):
"""
x.__getslice__(i, j) <==> x[i:j] Use of negative indices is not supported.
"""
pass def __ge__(self, y):
""" x.__ge__(y) <==> x>=y """
pass def __gt__(self, y):
""" x.__gt__(y) <==> x>y """
pass def __hash__(self):
""" x.__hash__() <==> hash(x) """
pass def __init__(self, string=''): # known special case of str.__init__
"""
str(object='') -> string Return a nice string representation of the object.
If the argument is a string, the return value is the same object.
# (copied from class doc)
"""
pass def __len__(self):
""" x.__len__() <==> len(x) """
pass def __le__(self, y):
""" x.__le__(y) <==> x<=y """
pass def __lt__(self, y):
""" x.__lt__(y) <==> x<y """
pass def __mod__(self, y):
""" x.__mod__(y) <==> x%y """
pass def __mul__(self, n):
""" x.__mul__(n) <==> x*n """
pass @staticmethod # known case of __new__
def __new__(S, *more):
""" T.__new__(S, ...) -> a new object with type S, a subtype of T """
pass def __ne__(self, y):
""" x.__ne__(y) <==> x!=y """
pass def __repr__(self):
""" x.__repr__() <==> repr(x) """
pass def __rmod__(self, y):
""" x.__rmod__(y) <==> y%x """
pass def __rmul__(self, n):
""" x.__rmul__(n) <==> n*x """
pass def __sizeof__(self):
""" S.__sizeof__() -> size of S in memory, in bytes """
pass def __str__(self):
""" x.__str__() <==> str(x) """
pass str str Code

2.字符串常用方法:

(1)capitalize:将首字母大写

1 >>> name = 'hello'
2 >>> name.capitalize()
3 'Hello'

(2)center/ljust/rjust:固定字符串长度,居中/居左/居右 ,下面是使用示例,当然没有正常人会上来就这么用,一般用在打印列表和字典的时候整理格式。

1 >>> str1='zhenghao love xiaokai'
2 >>> str1.center(30,'*') #设置格式左对齐,其余剩余部分由‘*’填充
3 '****zhenghao love xiaokai*****'
4 >>> str1.ljust(30, ) #设置格式左对齐,其余剩余部分由空格填充
5 'zhenghao love xiaokai '
6 >>> str1.rjust(30,'$') #设置格式左对齐,其余剩余部分由‘$’填充
7 '$$$$$$$$$zhenghao love xiaokai'
8 >>>

(3)count:子序列个数,用来统计一个字符串中包含指定子序列的个数。这个子序列可以是一个字符,也可以是多个字符~~

1 >>> str1 = 'hello,world'
2 >>> str1.count('o')
3 2
4 >>> str1.count('he')
5 1

(4)encode/decode:编码/解码,如下左图,各个编码之间是不能直接转换的,计算机内存中默认存储的编码格式是unicode,所以当我们需要将编码在utf8和gbk之间转换的时候,都需要和unicode做操作。
       我的终端编码是gbk编码的,当我创建一个string = '景'时,string就被存储成gbk格式。此时我想把gbk格式转换成utf8格式,就要先将原gbk格式的string转换成unicode格式,然后再将unicode转换成utf8格式。如下右图,老师说,把这个字整乱码了我们的目的就达到了,哈~

(5)endswith:是否以...(子串)结尾。这里的子串依然可以是一个或多个字符。

1 >>> str1 = 'hello,Have a nice day'
2 >>> str1.endswith('day')
3 True

(6)expandtabs:将tab转换成空格,默认一个tab转换成8个空格。当然这里也可以自行指定转换成多少个空格,要不是怕写不下,我就指定它转成千八百个。。。

1 >>> name = '    E'
2 >>> name.expandtabs()
3 ' E'
4 >>> name.expandtabs(20)
5 ' E'

(7)find:返回字符串中第一个子序列的下标。

      rfind:和find用法一样,只是它是从右向左查找

          index:和find的左右一致,只是find找不到的时候会返回-1,而index找不到的时候会报错

      值得注意的是,当我们在一个字符串中查找某一个子序列的时候,如果这个字符串中含有多个子序列,只会返回第一个找到的下标,不会返回其他的。

   1 >>> name = 'hello,e,how are you'
   2 >>> name.find('o')
 3 4
4 >>> name.find('t')
5 -1
6 >>> name.index('e')
7 1
8 >>> name.index('t')
9
10 Traceback (most recent call last):
11 File "<pyshell#234>", line 1, in <module>
12 name.index('t')
13 ValueError: substring not found

(8)format:各种格式化,动态参数。

(9)isalnum/isalpha/isdigit/isspace/islower/istitle/isupper:是否是字母或数字/是否字母/是否数字/是否空格/是否小写/是否标题/是否全大写,总之都是一些判断的方法,返回的不是True就是False。。。

(10)partition/split:这两个方法都用来分割。

  partition会将指定的子串串提取并将子串两侧内容分割,只匹配一次,并返回元祖;

  split会根据指定子串,将整个字符串所有匹配的子串匹配到并剔除,将其他内容分割,返回数组。

1 >>> food = 'apple,banana,chocolate'
2 >>> food.split(',')
3 ['apple', 'banana', 'chocolate']
4 >>> food.partition(',')
5 ('apple', ',', 'banana,chocolate')

(11)replace:替换。会替换字符串中所有符合条件的子串。。。原谅我的chinglish。。。

1 >>> str1 = 'I\'m Rita,Do you remember,Rita?'
2 >>> str1.replace('Rita','Eva')
3 "I'm Eva,Do you remember,Eva?"

(12)swapcase:大写变小写,小写变大写

1 >>> str1 = 'I\'m Eva'
2 >>> str1.swapcase()
3 "i'M eVA"

(13)translate:替换,删除字符串。这个方法的使用比较麻烦,在使用前需要引入string类,并调用其中的maketrans方法建立映射关系。这样,在translate方法中,加入映射参数,就可以看到效果了。如下‘aeiou’分别和‘12345’建立了映射关系,于是在最后,aeiou都被12345相应的替换掉了,translate第二个参数是删除,它删除了所有的‘.’

1 >>> in_tab = 'aeiou'
2 >>> out_tab = '12345'
3 >>> import string
4 >>> transtab = string.maketrans(in_tab,out_tab)
5 >>> str = 'this is a translate example...wow!'
6 >>> str1 = 'this is a translate example...wow!'
7 >>> print str1.translate(transtab,'..')
8 th3s 3s 1 tr1nsl1t2 2x1mpl2w4w!

3.字符串转义字符:

如果字符串内部既包含'又包含"怎么办?可以用转义字符\来标识,比如:

'I\'m \"OK\"!'

表示的字符串内容是:

I'm "OK"! 

转义字符\可以转义很多字符,比如\n表示换行,\t表示制表符,字符\本身也要转义,所以\\表示的字符就是\,可以在Python的交互式命令行用print()打印字符串看看:

 >>> print('I\'m ok.')
I'm ok.
>>> print('I\'m learning\nPython.')
I'm learning
Python.
>>> print('\\\n\\')
\
\

如果字符串里面有很多字符都需要转义,就需要加很多\,为了简化,Python还允许用r''表示''内部的字符串默认不转义,可以自己试试:

 >>> print('\\\t\\')
\ \
>>> print(r'\\\t\\')
\\\t\\

如果字符串内部有很多换行,用\n写在一行里不好阅读,为了简化,Python允许用'''...'''的格式表示多行内容,可以自己试试:

  >>> print('''line1

 ... line2
... line3''')
line1
line2
line3

上面是在交互式命令行内输入,注意在输入多行内容时,提示符由>>>变为...,提示你可以接着上一行输入。如果写成程序,就是:

 print('''line1
line2
line3''')

多行字符串'''...'''还可以在前面加上r使用,请自行测试。

4.字符串格式化,占位符:

在Python中,采用的格式化方式和C语言是一致的,用%实现,举例如下:

 >>> 'Hello, %s' % 'world'
'Hello, world'
>>> 'Hi, %s, you have $%d.' % ('zh', 1000000)
'Hi, zh, you have $1000000.'

你可能猜到了,%运算符就是用来格式化字符串的。在字符串内部,%s表示用字符串替换,%d表示用整数替换,有几个%?占位符,后面就跟几个变量或者值,顺序要对应好。如果只有一个%?,括号可以省略。

常见的占位符有:

%d 整数
%f 浮点数
%s 字符串
%x 十六进制整数

其中,格式化整数和浮点数还可以指定是否补0和整数与小数的位数:

 >>> '%2d-%02d' % (3, 1)
' 3-01'
>>> '%.2f' % 3.1415926
'3.14'

如果你不太确定应该用什么,%s永远起作用,它会把任何数据类型转换为字符串:

 >>> 'Age: %s. Gender: %s' % (25, True)
'Age: 25. Gender: True’

有些时候,字符串里面的%是一个普通字符怎么办?这个时候就需要转义,用%%来表示一个%

 >>> 'growth rate: %d %%' % 7
'growth rate: 7 %'

其实,上面这种格式化方法,常常被认为是太“古老”了。因为在 Python 中还有新的格式化方法。

 >>> s1 = "I like {}".format("python")
>>> s1
'I like python'
>>> s2 = "Suzhou is more than {} years. {} lives in here.".format(2500, "qiwsir")
>>> s2
'Suzhou is more than 2500 years. qiwsir lives in here.'

这就是 Python 非常提倡的 string.format()的格式化方法,其中 {} 作为占位符。

这种方法真的是非常好,而且非常简单,只需要将对应的东西,按照顺序在 format 后面的括号中排列好,分别对应占位符 {} 即可。我喜欢的方法。

如果你觉得还不明确,还可以这样来做。

 >>> print "Suzhou is more than {year} years. {name} lives in here.".format(year=2500, name="qiwsir")
Suzhou is more than 2500 years. qiwsir lives in here.

真的很简洁,堪称优雅。

其实,还有一种格式化的方法,被称为“字典格式化”,这里仅仅列一个例子,如果看官要了解字典的含义,本教程后续会有的。

 >>> lang = "Python"
>>> print "I love %(program)s"%{"program":lang}
I love Python

列举了三种基本格式化的方法,你喜欢那种?我推荐:string.format()

5.字符串的索引和切片

例如这样一个字符串 Python,它就是几个字符:P,y,t,h,o,n,排列起来。这种排列是非常严格的,不仅仅是字符本身,而且还有顺序,换言之,如果某个字符换了,就编程一个新字符串了;如果这些字符顺序发生变化了,也成为了一个新字符串。在 Python 中,把像字符串这样的对象类型(后面还会冒出来类似的其它有这种特点的对象类型,比如列表),统称为序列。顾名思义,序列就是“有序排列”。

 >>> str='python'
>>> str[0]
'p'
>>> str[:4]
'pyth'
>>> str[:]
'python'
>>> str[1:4]
'yth'
>>> str[-3:-1]
'ho'
>>> str.index('t')
2
>>>

6.字符串连接

 >>> a='三毛'
>>> s='荷西'
>>> z=a+s
>>> z
'\xe4\xb8\x89\xe6\xaf\x9b\xe8\x8d\xb7\xe8\xa5\xbf'
>>> print(z)
三毛荷西
>>>

 

python基础知识2——基本的数据类型——整型,长整型,浮点型,字符串的更多相关文章

  1. python基础知识3——基本的数据类型2——列表,元组,字典,集合

    磨人的小妖精们啊!终于可以归置下自己的大脑啦,在这里我要把--整型,长整型,浮点型,字符串,列表,元组,字典,集合,这几个知识点特别多的东西,统一的捯饬捯饬,不然一直脑袋里面乱乱的. 一.列表 1.列 ...

  2. python基础知识梳理----3基本数据类型,int,bool,str ,for 循环,迭代

    一:python的基本类型 1.int  -----整数,主要进行数学运算 2.str  -----字符串,可以保存少量数据,并进行相关操作, 3. bool ---布尔类型,判断真假 4.list ...

  3. 5000字2021最新Python基础知识第一阶段:数据类型

    1 编程规范 注释 python注释也有自己的规范,在文章中会介绍到.注释可以起到一个备注的作用,团队合作的时候,个人编写的代码经常会被多人调用,为了让别人能更容易理解代码的通途,使用注释是非常有效的 ...

  4. python基础知识梳理-----4基本数据类型,list ,tuple 操作 ,增删该查,以及其他功能函数

    一:列表的增加 1: append() lis = ['张三','李四','王二码子','李鹏智障'] lis.append('赵武')      # 这种加法是放在最后 print(lis) 输出  ...

  5. python基础知识之列表、元祖、字典、集合、字符串。

    1.可变类型之列表 列表用 [ ]来定义是可变的,可以通过索引值来去查询里面的字段可以可以追加,删除等 names='zhangyang guyun xiangpeng xuliangwei' nam ...

  6. Python开发【第二篇】:Python基础知识

    Python基础知识 一.初识基本数据类型 类型: int(整型) 在32位机器上,整数的位数为32位,取值范围为-2**31-2**31-1,即-2147483648-2147483647 在64位 ...

  7. python基础知识小结-运维笔记

    接触python已有一段时间了,下面针对python基础知识的使用做一完整梳理:1)避免‘\n’等特殊字符的两种方式: a)利用转义字符‘\’ b)利用原始字符‘r’ print r'c:\now' ...

  8. Python 基础知识(一)

    1.Python简介 1.1.Python介绍 python的创始人为吉多·范罗苏姆(Guido van Rossum).1989年的圣诞节期间,吉多·范罗苏姆(中文名字:龟叔)为了在阿姆斯特丹打发时 ...

  9. python基础知识(一)

    Python基础知识 计算基础知识 1.cpu 人类的大脑 运算和处理问题 2.内存 临时存储数据 断电就消失了 3.硬盘 永久存储数据 4.操作系统 调度硬件设备之间数据交互 python的应用和历 ...

随机推荐

  1. dotNet下的一套解决方案

    很久没在博客园写文章了,打算把一直由自己一个人写的一整套系统开放出来,今天先放一些截图及可以演示的地址! 这套系统包含数据层(HB.Data).计划任务(HB.PlanTask).日志系统(HB.Lo ...

  2. bzoj1553: XOR网络

    Description   计算给定范围内有多少种输入可以使输出为1. 我们假设3 < n < 100, 3 < m < 3000,而且网络中的门是用1到m之间的数任意编号的. ...

  3. [经验交流] Active-Active 方式设置 kubernetes master 多节点高可用

    关于 kubernetes master 多节点以及高可用,网上的方法多采取 Active-Standby 方式,即: 通过 pacemaker 等软件使得某种 master 服务(apiserver ...

  4. 获取小众ftp服务器指定目录内容列表

    今天获取小众ftp服务器指定目录内容列表时费劲急了. ///parama url="ftp://x.x.x.x/dir_name" public string GetFTPDir( ...

  5. [Mongodb] Tarball二进制包安装过程

    一.缘由: 用在线安装的方式安装mongodb,诚然很方便.但文件过于分散,如果在单机多实例的情况下,就不方便管理. 对于数据库的管理,我习惯将所有数据(配置)文件放在一个地方,方便查找区分. 二.解 ...

  6. js正则表达式学习

    //几种字符串操作:var str = 'abcdef'; alert(str.search('b')); //弹出1:返回的是b在str中的位置:如果找不到返回-1: alert(str.subst ...

  7. terminator 安装及使用

    1. 安装 $ sudo apt-get install terminator 2. 右键设置首选项 背景设置为0.8透明度, 字体挤在一起:在ubuntu下请选择mono后缀的字体就可以了 3. 使 ...

  8. [转]云计算研究必备——精典Google论文

    Google云计算技术奠定其在业界的领先地位,收集经典云计算技术公开文章供大家研究学习: 01)GFS-The Google File System 02) Bigtable - A Distribu ...

  9. [转载]反无人机企业DroneShield利用声音识别侦测无人机

    原文:http://www.cnbeta.com/articles/495071.htm 无人机产业正在蓬勃发展,受益的不仅仅是那些生产小型飞行设备的企业.专家估计仅在澳大利亚就有5万架商用无人机以及 ...

  10. SpringMVC工作环境搭建 配置文件

    web.xml配置 在服务器端容器启动之前加载配置文件的顺序:context-param>listener>filter>servlet //容器配置application上下文的时 ...