前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Python之运算符以及基本数据类型的object

Python之运算符以及基本数据类型的object

作者头像
用户1173509
发布2018-01-17 14:59:15
2.4K0
发布2018-01-17 14:59:15
举报
文章被收录于专栏:CaiRuiCaiRuiCaiRui

一、运算符

1、算术运算符

%   求余运算

**    幂-返回x的y次幂

//    取整数-返回商的整数部分,例:9//2输出结果是4

2、比较运算符

==  等于

!=  不等于

<>  不等于

>  大于 

<  小于  

>=  大于等于

<=  小于等于

3、赋值运算

=  简单的赋值

+=  加法赋值运算,c += a等效于c = c + a

-=  减法赋值运算

*=  乘法赋值运算

/=  除法赋值运算

%=  取模赋值运算

**=  幂赋值运算符

//=  取整除赋值运算符

4、in

in  如果在指定的序列中找到值返回True,否则返回False

not in  如果在指定的序列中没有找到值返回True,否则返回False

二、基本数据类型

1、数字(int)

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

2、字符串(str)

def capitalize(self): # real signature unknown; restored from __doc__    """    S.capitalize() -> str        Return a capitalized version of S, i.e. make the first character    have upper case and the rest lower case.(返回第一个字符大写,其他小写)
    """    return ""
def casefold(self): # real signature unknown; restored from __doc__    """    S.casefold() -> str        Return a version of S suitable for caseless comparisons.  (将大写变成小写)    """    return ""
def center(self, width, fillchar=None): # real signature unknown; restored from __doc__    """    S.center(width[, fillchar]) -> str        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): # 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, encoding='utf-8', errors='strict'): # real signature unknown; restored from __doc__  (编码的意思)    """    S.encode(encoding='utf-8', errors='strict') -> bytes        Encode S using the codec registered for encoding. Default encoding    is 'utf-8'. 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 can handle UnicodeEncodeErrors.    """    return b""
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.(返回True,如果字符串以指定的后缀结尾,否则False)    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=8): # real signature unknown; restored from __doc__  (把字符串中的Tab符号('\t')转为空格,Tab符号默认的空格数是8个,也可以自己指定)    """    S.expandtabs(tabsize=8) -> str        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.  (如果不给定tabsize,假定有8个字符的选项卡大小)    """    return ""
def find(self, sub, start=None, end=None): # real signature unknown; restored from __doc__ 显示位置 (检测字符串中是否包含子字符串str,如果指定开始和结束范围,则检查指定范围内,如果包含子字符串返回开始的索引值,否则返回-1)    """    S.find(sub[, start[, end]]) -> int        Return the lowest index in S where substring sub is found,  (返回找到substring子的字符串中最低索引,这样的子被包含在字符串[start:end]中。可选参数的开始和结束被解释为片表示法)    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.(返回格式化的字符串,使用来自args和kwargs的替换)    The substitutions are identified by braces ('{' and '}').(用括号({'and'}))来标识替换。    """    pass
def index(self, sub, start=None, end=None): # real signature unknown; restored from __doc__  (和find差不多)    """    S.index(sub[, start[, end]]) -> int        Return the lowest index in S where substring sub is found,   (返回找到提交字符串子字符串的最低索引,这样的子被包含在S[start.end]中。可选参数的开始和结束被解释为片表示法)    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): # real signature unknown; restored from __doc__    """    S.isalnum() -> bool        Return True if all characters in S are alphanumeric    and there is at least one character in S, False otherwise.  (如果字符串中的所有字符都是字母数字,返回True,在字符串中至少有一个字符,是False)    """    return False
def isalpha(self): # real signature unknown; restored from __doc__  (检测字符串是否只由字母组成)    """    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 isdecimal(self): # real signature unknown; restored from __doc__  (检查字符串中是否只包含十进制字符)    """    S.isdecimal() -> bool        Return True if there are only decimal characters in S,    False otherwise.    """    return False
def isdigit(self): # real signature unknown; restored from __doc__  (检查字符串是否由数字组成)    """    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 isidentifier(self): # real signature unknown; restored from __doc__  (not important)    """    S.isidentifier() -> bool        Return True if S is a valid identifier according  (如果字符串是有效的标识符,则返回True语言的定义)    to the language definition.        Use keyword.iskeyword() to test for reserved identifiers  (使用keyword.is关键词()来测试保留标识符)    such as "def" and "class".    """    return False
def islower(self): # real signature unknown; restored from __doc__  (not important)    """    S.islower() -> bool        Return True if all cased characters in S are lowercase and there is  (如果在字符串中所有字符都是小写,则返回True。否则False)    at least one cased character in S, False otherwise.    """    return False
def isnumeric(self): # real signature unknown; restored from __doc__  (检查字符串是否只由数字组成。这种方法只针对unicode对象。)    """    S.isnumeric() -> bool        Return True if there are only numeric characters in S,    False otherwise.    """    return False
def isprintable(self): # real signature unknown; restored from __doc__      """    S.isprintable() -> bool        Return True if all characters in S are considered    (如果考虑字符串中的所有字符,返回True)    printable in repr() or S is empty, False otherwise.    """    return False
def isspace(self): # real signature unknown; restored from __doc__    """    S.isspace() -> bool        Return True if all characters in S are whitespace    and there is at least one character in S, False otherwise.  (如果在字符串中所有字符串都是空格,则返回True)    """    return False
def istitle(self): # real signature unknown; restored from __doc__    """    S.istitle() -> bool        Return True if S is a titlecased string and there is at least one  (返回True如果字符串是一个标题字符串,至少有一个字符在字符串中,否则为False)    character in S, i.e. upper- and titlecase characters may only    follow uncased characters and lowercase characters only cased ones.    Return False otherwise.    """    return False
def isupper(self): # real signature unknown; restored from __doc__    """    S.isupper() -> bool        Return True if all cased characters in S are uppercase and there is  (如果字符串中所有字符都是大写,那么返回True,否则False)    at least one cased character in S, False otherwise.    """    return False
def join(self, iterable): # real signature unknown; restored from __doc__  (用于将序列中的元素以指定的字符连接生成一个新的字符串)    """    S.join(iterable) -> str        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): # real signature unknown; restored from __doc__  (返回字符串左对齐的字符串长度。填充是通过指定的fillchar(默认为空格)。如果宽度小于len(s)返回原始字符串)    """    S.ljust(width[, fillchar]) -> str        Return S left-justified in a Unicode string of length width. Padding is    done using the specified fill character (default is a space).    """    return ""
def lower(self): # real signature unknown; restored from __doc__  (转换字符串中所有大写为小写)    """    S.lower() -> str        Return a copy of the string S converted to lowercase.    """    return ""
def lstrip(self, chars=None): # real signature unknown; restored from __doc__  ()    """    S.lstrip([chars]) -> str        Return a copy of the string S with leading whitespace removed.    (将字符串的副本返回,并删除主要空白)    If chars is given and not None, remove characters in chars instead.    (如果给定字符,而不是None,则删除字符)    """    return ""
def maketrans(self, *args, **kwargs): # real signature unknown  (用于创建字符映射的转换表,对于接受两个参数的最简单的调用方式,第一个参数是字符串,表示需要转换的字符,第二个参数也是字符串表示转换的目标。)    """    Return a translation table usable for str.translate().  (两个字符串的长度必须相同,为一一对应的关系)        If there is only one argument, it must be a dictionary mapping Unicode    ordinals (integers) or characters to Unicode ordinals, strings or None.    Character keys will be then converted to ordinals.    If there are two arguments, they must be strings of equal length, and    in the resulting dictionary, each character in x will be mapped to the    character at the same position in y. If there is a third argument, it    must be a string, whose characters will be mapped to None in the result.    """    pass
def partition(self, sep): # real signature unknown; restored from __doc__  (用来根据指定的分隔符将字符串进行分割。如果字符串包含指定的分隔符,则返回一个3元组,第一个为分隔符左边的子串,第二个为分隔符本身,第三个为分隔符右边的子串)    """    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
#!/usr/bin/python

str = "http://www.w3cschool.cc/"

print str.partition("://")
输出结果为:
('http', '://', 'www.w3cschool.cc/')
def replace(self, old, new, count=None): # real signature unknown; restored from __doc__  (把字符串中的old(旧字符串)替换成new(新字符串),如果指定第三个参数max,则替换不超过max次)    """    S.replace(old, new[, count]) -> str        Return a copy of 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 ""
#!/usr/bin/python

str = "this is string example....wow!!! this is really string";
print str.replace("is", "was");
print str.replace("is", "was", 3);
以上实例输出结果如下:
thwas was string example....wow!!! thwas was really string
thwas was string example....wow!!! thwas is really string
def rfind(self, sub, start=None, end=None): # real signature unknown; restored from __doc__  (返回字符串最后一次出现的位置(从右向左查询),如果没有匹配项则返回-1)    """    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
#!/usr/bin/python

str = "this is really a string example....wow!!!";
substr = "is";

print str.rfind(substr);
print str.rfind(substr, 0, 10);
print str.rfind(substr, 10, 0);

print str.find(substr);
print str.find(substr, 0, 10);
print str.find(substr, 10, 0);
以上实例输出结果如下:
5
5
-1
2
2
-1
def rjust(self, width, fillchar=None): # real signature unknown; restored from __doc__  (删除string字符串末尾的指定字符(默认为空格))    """    S.rjust(width[, fillchar]) -> str        Return S right-justified in a string of length width. Padding is    done using the specified fill character (default is a space).    """    return ""
#!/usr/bin/python

str = "     this is string example....wow!!!     ";
print str.rstrip();
str = "88888888this is string example....wow!!!8888888";
print str.rstrip('8');
以上实例输出结果如下:
     this is string example....wow!!!
88888888this is string example....wow!!!
def rpartition(self, sep): # real signature unknown; restored from __doc__    (根据指定的分隔符将字符串进行分割。如果字符串包含指定的分隔符,则返回一个3元的组,第一个为分隔符左边的子串,第二个为分隔符本身,第三个为分隔符右边的子串)    """    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
#!/usr/bin/python

str = "http://www.w3cschool.cc/"

print str.partition("://")
输出结果为:
('http', '://', 'www.w3cschool.cc/')
def split(self, sep=None, maxsplit=-1): # real signature unknown; restored from __doc__  (通过指定分隔符对字符串进行切片,如果参数num有指定值,则仅分隔num个字符串)    """    S.split(sep=None, maxsplit=-1) -> list of strings        Return a list of the words in 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 []
#!/usr/bin/python

str = "Line1-abcdef \nLine2-abc \nLine4-abcd";
print str.split( );
print str.split(' ', 1 );
以上实例输出结果如下:
['Line1-abcdef', 'Line2-abc', 'Line4-abcd']
['Line1-abcdef', '\nLine2-abc \nLine4-abcd']
def splitlines(self, keepends=None): # real signature unknown; restored from __doc__  (按照行分隔,返回一个包含行作为元素的列表,如果参数keepends为False,不包含换行符,如果为True,则保留换行符)    """    S.splitlines([keepends]) -> 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 []
#!/usr/bin/python

str1 = 'ab c\n\nde fg\rkl\r\n'
print str1.splitlines();

str2 = 'ab c\n\nde fg\rkl\r\n'
print str2.splitlines(True)
以上实例输出结果如下:
['ab c', '', 'de fg', 'kl']
['ab c\n', '\n', 'de fg\r', 'kl\r\n']
def startswith(self, prefix, start=None, end=None): # real signature unknown; restored from __doc__  (用于检查字符串是否是以指定字符串开头,如果是则返回True,否则)    """      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
#!/usr/bin/python

str = "this is string example....wow!!!";
print str.startswith( 'this' );
print str.startswith( 'is', 2, 4 );
print str.startswith( 'this', 2, 4 );
以上实例输出结果如下:
True
True
False
def strip(self, chars=None): # real signature unknown; restored from __doc__  (用于移除字符串头尾指定的字符,默认为空格)    """    S.strip([chars]) -> str        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.    """    return ""
#!/usr/bin/python

str = "0000000this is string example....wow!!!0000000";
print str.strip( '0' );
以上实例输出结果如下:
this is string example....wow!!!
def swapcase(self): # real signature unknown; restored from __doc__    (用于对字符串的大小写字母进行转换)    """    S.swapcase() -> str        Return a copy of S with uppercase characters converted to lowercase    and vice versa.    """    return ""
#!/usr/bin/python

str = "this is string example....wow!!!";
print str.swapcase();

str = "THIS IS STRING EXAMPLE....WOW!!!";
print str.swapcase();
以上实例输出结果如下:
this is string example....wow!!!
def translate(self, table): # real signature unknown; restored from __doc__    (根据参数table给出的表(包含256个字符)转换字符串的字符,要过滤掉的字符放到del参数中)    """    S.translate(table) -> str        Return a copy of the string S in which each character has been mapped    through the given translation table. The table must implement    lookup/indexing via __getitem__, for instance a dictionary or list,    mapping Unicode ordinals to Unicode ordinals, strings, or None. If    this operation raises LookupError, the character is left untouched.    Characters mapped to None are deleted.    """    return ""
#!/usr/bin/python

from string import maketrans   # 引用 maketrans 函数。

intab = "aeiou"
outtab = "12345"
trantab = maketrans(intab, outtab)

str = "this is string example....wow!!!";
print str.translate(trantab);
以上实例输出结果如下:
th3s 3s str3ng 2x1mpl2....w4w!!!
以上实例去除字符串中的 'x' 和 'm' 字符:
#!/usr/bin/python

from string import maketrans   # Required to call maketrans function.

intab = "aeiou"
outtab = "12345"
trantab = maketrans(intab, outtab)

str = "this is string example....wow!!!";
print str.translate(trantab, 'xm');
以上实例输出结果:
th3s 3s str3ng 21pl2....w4w!!!

3.列表(形式:name_list = ["cairui","caicai","aiai"])

def append(self, p_object): # real signature unknown; restored from __doc__  (在列尾末尾添加新的对象)    """ L.append(object) -> None -- append object to end """    pass
#!/usr/bin/python

aList = [123, 'xyz', 'zara', 'abc'];
aList.append( 2009 );
print "Updated List : ", aList;
以上实例输出结果如下:
Updated List :  [123, 'xyz', 'zara', 'abc', 2009]
def clear(self): # real signature unknown; restored from __doc__    (函数用于清空列表,类似于del a[:])    """ L.clear() -> None -- remove all items from L """    pass
#!/usr/bin/python3

list1 = ['Google', 'Runoob', 'Taobao', 'Baidu']
list1.clear()
print ("列表清空后 : ", list1)
以上实例输出结果如下:
列表清空后 :  []
def copy(self): # real signature unknown; restored from __doc__  (用于复制列表,类似于a[:])    """ L.copy() -> list -- a shallow copy of L """    return []
#!/usr/bin/python3

list1 = ['Google', 'Runoob', 'Taobao', 'Baidu']
list2 = list1.copy()
print ("list2 列表: ", list2)
以上实例输出结果如下:
list2 列表:  ['Google', 'Runoob', 'Taobao', 'Baidu']
def count(self, value): # real signature unknown; restored from __doc__      (用于统计某个元素在列表中出现的次数)    """ L.count(value) -> integer -- return number of occurrences of value """    return 0
#!/usr/bin/python

aList = [123, 'xyz', 'zara', 'abc', 123];

print "Count for 123 : ", aList.count(123);
print "Count for zara : ", aList.count('zara');
以上实例输出结果如下:
Count for 123 :  2
Count for zara :  1
def extend(self, iterable): # real signature unknown; restored from __doc__    """ L.extend(iterable) -> None -- extend list by appending elements from the iterable """  (函数用于在列表末尾一次性追加另一个序列中的多个值)    pass
#!/usr/bin/python

aList = [123, 'xyz', 'zara', 'abc', 123];
bList = [2009, 'manni'];
aList.extend(bList)

print "Extended List : ", aList ;
以上实例输出结果如下:
Extended List :  [123, 'xyz', 'zara', 'abc', 123, 2009, 'manni']
def index(self, value, start=None, stop=None): # real signature unknown; restored from __doc__  (用于从列表中找出某个值第一个匹配的索引位置)    """    L.index(value, [start, [stop]]) -> integer -- return first index of value.    Raises ValueError if the value is not present.    """    return 0
#!/usr/bin/python

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
def insert(self, index, p_object): # real signature unknown; restored from __doc__  (用于将指定对象插入列表的指定位置)    """ L.insert(index, object) -- insert object before index """    pass
#!/usr/bin/python

aList = [123, 'xyz', 'zara', 'abc']

aList.insert( 3, 2009)

print "Final List : ", aList
以上实例输出结果如下:
Final List : [123, 'xyz', 'zara', 2009, 'abc']
def remove(self, value): # real signature unknown; restored from __doc__  (用于移除列表中某个值的第一个匹配项)    """    L.remove(value) -> None -- remove first occurrence of value.    Raises ValueError if the value is not present.    """    pass
#!/usr/bin/python3

list1 = ['Google', 'Runoob', 'Taobao', 'Baidu']
list1.remove('Taobao')
print ("列表现在为 : ", list1)
list1.remove('Baidu')
print ("列表现在为 : ", list1)
以上实例输出结果如下:
列表现在为 :  ['Google', 'Runoob', 'Baidu']
列表现在为 :  ['Google', 'Runoob']
def reverse(self): # real signature unknown; restored from __doc__  (用于反向列表中元素)    """ L.reverse() -- reverse *IN PLACE* """    pass
#!/usr/bin/python3

list1 = ['Google', 'Runoob', 'Taobao', 'Baidu']
list1.reverse()
print ("列表反转后: ", list1)
以上实例输出结果如下:
列表反转后:  ['Baidu', 'Taobao', 'Runoob', 'Google']
def sort(self, key=None, reverse=False): # real signature unknown; restored from __doc__  (用于对原列表进行排序,如果指定参数,则使用比较函数指定的比较函数)    """ L.sort(key=None, reverse=False) -> None -- stable sort *IN PLACE* """    pass
#!/usr/bin/python3

list1 = ['Google', 'Runoob', 'Taobao', 'Baidu']
list1.sort()
print ("列表排序后 : ", list1)
以上实例输出结果如下:
列表排序后 :  ['Baidu', 'Google', 'Runoob', 'Taobao']

4、字典(dict)

形式:

user_info = {

  "name":"cairui",

  "age":19,

  "gender":'M'

}

def clear(self): # real signature unknown; restored from __doc__  (用于删除字典内的所有元素)    """ D.clear() -> None.  Remove all items from D. """    pass
#!/usr/bin/python3

dict = {'Name': 'Zara', 'Age': 7}

print ("字典长度 : %d" %  len(dict))
dict.clear()
print ("字典删除后长度 : %d" %  len(dict))
以上实例输出结果为:
字典长度 : 2
字典删除后长度 : 0
def get(self, k, d=None): # real signature unknown; restored from __doc__  (返回指定键的值,如果值不在字典中返回默认值)    """ D.get(k[,d]) -> D[k] if k in D, else d.  d defaults to None. """    pass
#!/usr/bin/python3 

dict = {'Name': 'Runoob', 'Age': 27}

print ("Age 值为 : %s" %  dict.get('Age'))
print ("Sex 值为 : %s" %  dict.get('Sex', "NA"))
以上实例输出结果为:
Age 值为 : 27
Sex 值为 : NA

4、enumerate用法:自动生成一列,默认从0开始自增1,也可以自己指定字符串转换为数字int(字符串)

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2017-08-15 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 一、运算符
    • 2、比较运算符
      • 3、赋值运算
        • 4、in
        • 二、基本数据类型
          • 1、数字(int)
            • 2、字符串(str)
              • 3.列表(形式:name_list = ["cairui","caicai","aiai"])
                • 4、enumerate用法:自动生成一列,默认从0开始自增1,也可以自己指定字符串转换为数字int(字符串)
                领券
                问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档