python数据类型总结_python之数据类型总结

1、运算符:

(1)判断运算符:

运算符

描述

实例

in

表示一个元素在另一个元素里面,为真

“a” in “abc”

not in

表示一个元素不在另一个元素里面,为真

“d” not in “abc”

(2)、算术运算符:

运算符

描述

实例

+

加 表示两个对象相加

a + b输出结果30

-

减 表示一个数减去另一个数

a - b输出结果-10

*

乘 两个数相乘或是返回一个被重复若干次的字符串

a * b输出结果200

/

除 两个数相除

b / a 输出结果2

**

幂 返回一个数的n次幂

3 ** 3 输出结果27

%

取余 返回除法的余数

b % a 输出结果 0

//

取整数 返回商的整数部分

9 // 2输出结果4

(3)比较运算

运算符

描述

实例

==

等于 比较对象是否相等

a == b返回False

!=

不等于 比较两个对象是否不相等

a != b 返回True

<>

不等于 比较两个对象是否不相等

<> 和== 意思一样(不推荐使用)

>

大于 一个值大于一个值

a > b 返回False

<

小于 一个值小于一个值

a < b 返回True

>=

大于等于 一个值大于等于一个值

a >= b 返回False

<=

小于等于 一个值小于等于一个值

a <= b 返回True

(4)赋值运算符

运算符

描述

实例

=

简单的赋值运算符

c = a + b将a + b 结果赋值给c

+=

加法赋值运算符

c += a 等同于c = c + a

-=

减法赋值运算符

c -= a 等同于c = c - a

*=

乘法赋值运算符

c *= a 等同于c = c * a

/=

除法赋值运算符

c /= a 等同于c = c / a

%=

取模赋值运算符

c %= a 等同于c = c % a

**=

幂赋值运算符

c **= a 等同于c = c ** a

//=

取整数商赋值运算符

c // =a 等同于c = c // a

(5)逻辑运算符

运算符

描述

实例

and

布尔”与”-如果x为False,x and y返回False否则它返回y的计算值

(a and b)返回true

or

布尔”或”-如果是true,它返回True,否则它返回y的计算值

(a or b)返回True

not

布尔”非”-如果x为True,返回False,如果x为False,它返回True

not(a and b)返回false

2、字符串列表的切片与索引:

2.1字符串索引取值:

s = 'alexissb'

s2 = s[2] #取索引为2的值

print(s2)

s = 'alexissb'

s3 = s[5] #取索引为5的值

print(s3)

2.2字符串切片取值:

s = 'alexissb'

s4 = s[1:5] #通过切片取>=1且<5的索引的值

print(s4)

s = 'alexissb'

s5 = s[:] #如果索引从0开始则:前面不用写,后面不写表示取全部值

print(s5)

s = 'alexissb'

s6 = s[-1] #索引为-1的时候表示取字符串后面最后一个值

print(s6)

2.3添加步长取值:

s = 'alexissb'

s7 = s[::2] #::2表示从头取到尾,每隔一个字符取一个字符

print(s7)

s = 'alexissb'

s8 = s[:7:3] #每隔两个字符取一个字符

print(s8)

PS:列表的索引和切片与字符串的一样,就不在过多的赘述了。

3、整形,字符串,列表,字典常用功能解析:

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

示例:

i = 19

s = i.bit_length()

print(s)

结果:

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 ""

示例:

s = "twonss"

s1 = s.capitalize()

print(s1)

结果:

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 ""

示例:

s = "twonss"

s2 = s.center(20,"`")

print(s2)

结果:

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

示例:

s = "twonss"

s3 = s.count("s")

print(s3)

结果:

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

示例:

s = "twonss"

s4 = s.endswith('s')

print(s4)

结果:

def find(self, sub, start=None, end=None): # real signature unknown; restored from __doc__

""" ##查找字符串的对应字符的索引,只找第一个,如果不存在返回-1,还可以指定查找的开始和结束位置

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

示例1:(普通用法)

s = "twonss"

s5 = s.find('s')

print(s5)

结果:

示例2:(指定开始和结束位置)

s = "twonss"

s5 = s.find('o',1,4)

print(s5)

结果:

示例3:(查找不存在字符)

s = "twonss"

s6 = s.find('c')

print(s6)

结果:

def format(self, *args, **kwargs): # known special case of str.format

""" ##字符串内占位符替换为指定字符,等同于%s

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

示例1:(常规用法)

s = "I am {name} age is {num}"

s7 = s. format(name = 'alex',num = 10)

print(s7)

结果:

示例2:(顺序用法1)

s = "I am {0} age is {1} hobby {2}"

s7 = s. format('alex',10,'male')

print(s7)

结果:

示例3:(顺序用法3)

s = "I am {} age is {} hobby {}"

s7 = s. format('alex',10,'male')

print(s7)

结果:

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 ""

示例:

s = "I am {name} age is {num}"

s7 = s.format_map({'name':'alex','num':22})

print(s7)

结果:

def index(self, sub, start=None, end=None): # real signature unknown; restored from __doc__

""" ##和find功能一样,都是查找字符串中字符的索引,但是index找不到对应的索引会报错

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

Like S.find() but raise ValueError when the substring is not found.

"""

return 0

示例1:(常规查找)

s = "twonss"

s8 = s.index('s')

print(s8)

结果:

示例2:(字符不存在的情况)

s = "twonss"

s8 = s.index('p')

print(s8)

结果:

示例3:(指定开始结束位置)

s = "twonss"

s8 = s.index('s',2,6)

print(s8)

结果:

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.

"""

return False

示例:

s = "twonss112233"

s9 = s.isalnum()

print(s9)

结果:

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

示例:

s = "twonss"

s10 = s.isalpha()

print(s10)

结果:

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

示例:

s = "15700895672"

s11 = s.isdigit()

print(s11)

结果:

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 ""

示例:

l = ['alex', 'wusir', 'ritian']

l1 = ",".join(l)

print(l1)

结果:

def lower(self): # real signature unknown; restored from __doc__

""" ##字符串里的大写字母变小写

S.lower() -> str

Return a copy of the string S converted to lowercase.

"""

return ""

示例:

s = "TwoNSS"

s12 = s.lower()

print(s12)

结果:

def partition(self, sep): # real signature unknown; restored from __doc__

""" ##指定以什么为分割符,以最左边的分隔符为准

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

示例:

s = "twonss.com"

s13 = s.partition("o")

print(s13)

结果:

def split(self, sep=None, maxsplit=-1): # real signature unknown; restored from __doc__

""" ##可以指定任意字符串内有的字符为为分割符,结果显示的会是一个列表

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 []

示例:

s = "twonss.com"

s14 = s.split("o")

print(s14)

结果:

def startswith(self, prefix, start=None, end=None): # real signature unknown; restored from __doc__

""" ##以什么字符开头则为真

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

示例:

s = "twonss.com"

s15 = s.startswith('t')

print(s15)

s16 = s.startswith('p')

print(s16)

结果:

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 ""

示例:

s = " twonss.com\t\n"

s17 = s.strip()

print(s17)

结果:

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 ""

示例:

s = "TwoNss.Com"

s18 = s.swapcase()

print(s18)

结果:

def title(self): # real signature unknown; restored from __doc__

""" ##以非字母分割的每个单词的第一个字母大写

S.title() -> str

Return a titlecased version of S, i.e. words start with title case

characters, all remaining cased characters have lower case.

"""

return ""

示例:

s = "two&nss.c*o$m"

s19 = s.title()

print(s19)

结果:

def upper(self): # real signature unknown; restored from __doc__

""" ##字符串中所有字母大写

S.upper() -> str

Return a copy of S converted to uppercase.

"""

return ""

示例:

s = "twonss.com"

s20 = s.upper()

print(s20)

结果:

list列表解析:

插入功能

def append(self, p_object): # real signature unknown; restored from __doc__

""" ##在列表的最后追加内容,只能是一个数据类型

L.append(object) -> None -- append object to end """

pass

示例:

l = ['alex','eric','tom']

l.append('twonss')

print(l)

结果:

def extend(self, iterable): # real signature unknown; restored from __doc__

""" ##追加元素,如果是追加的是字符串,则会把字符串都拆分,如果是列表则列表里面有几个元素就会追加几个元素

L.extend(iterable) -> None -- extend list by appending elements from the iterable """

pass

示例1:(插入字符串类型)

l = ['alex','eric','tom']

l.extend('twonss')

print(l)

结果:

示例2:(插入列表类型)

l = ['alex','eric','tom']

l.extend(['twonss'])

print(l)

结果:

def insert(self, index, p_object): # real signature unknown; restored from __doc__

""" ##在指定列表索引的前面插入元素

L.insert(index, object) -- insert object before index """

pass

示例:

l = ['alex','eric','tom']

l.insert(1,'egon')

print(l)

结果:

def copy(self): # real signature unknown; restored from __doc__

"""

L.copy() -> list -- a shallow copy of L """

return []

def count(self, value): # real signature unknown; restored from __doc__

""" ##计算列表中指定的元素有几个

L.count(value) -> integer -- return number of occurrences of value """

return 0

示例:

l = ['alex','eric','tom']

l1 = l.count('alex')

print(l1)

结果:

def index(self, value, start=None, stop=None): # real signature unknown; restored from __doc__

""" ##和str中的index功能一样,都是通过元素找索引

L.index(value, [start, [stop]]) -> integer -- return first index of value.

Raises ValueError if the value is not present.

"""

return 0

示例:(通过元素查找索引,如果列表没有要查找的元素,则报错)

l = ['alex','eric','tom']

l2 = l.index('tom')

print(l2)

结果:

删除功能

def pop(self, index=None): # real signature unknown; restored from __doc__

""" ##根据索引删除列表元素

L.pop([index]) -> item -- remove and return item at index (default last).

Raises IndexError if list is empty or index is out of range.

"""

pass

示例1:(指定元素删除元素)

l = ['alex','eric','tom']

l.pop(1)

print(l)

结果:

示例2:(通过pop的返回值可以查看删除的元素)

l = ['alex','eric','tom']

l3 = l.pop(1)

print(l3)

结果:

def clear(self): # real signature unknown; restored from __doc__

""" ##清空整个列表

L.clear() -> None -- remove all items from L """

pass

示例:

l = ['alex','eric','tom']

l.clear()

print(l)

结果:

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

示例:

l = ['alex','eric','tom']

l.remove('tom')

print(l)

结果:

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

示例1:(正向排序)

l = [1,5,8,2,4,9,6,3]

l.sort()

print(l)

结果:

示例2:(数字排序并反转)

l = [1,5,8,2,4,9,6,3]

l.sort(reverse=True)

print(l)

结果:

def reverse(self): # real signature unknown; restored from __doc__

""" ##将列表反向排序

L.reverse() -- reverse *IN PLACE* """

pass

示例:

l = [1,5,8,2,4,9,6,3]

l.reverse()

print(l)

结果:

dict字典解析

def pop(self, k, d=None): # real signature unknown; restored from __doc__

""" ##指定key删除value

D.pop(k[,d]) -> v, remove specified key and return the corresponding value.

If key is not found, d is returned if given, otherwise KeyError is raised

"""

pass

示例:

d = {'name':'tom','age':22,'hobby':'male'}

d.pop('hobby')

print(d)

结果:

def clear(self): # real signature unknown; restored from __doc__

""" ##清空整个字典

D.clear() -> None. Remove all items from D. """

pass

示例:

d = {'name':'tom','age':22,'hobby':'male'}

d.clear()

print(d)

结果:

def popitem(self): # real signature unknown; restored from __doc__

""" ##随机删除键值对,python3.5的时候是随机删除,3.6的时候默认删除最后一个

D.popitem() -> (k, v), remove and return some (key, value) pair as a

2-tuple; but raise KeyError if D is empty.

"""

pass

示例:

d = {'name':'tom','age':22,'hobby':'male'}

d.popitem()

print(d)

结果:

def setdefault(self, k, d=None): # real signature unknown; restored from __doc__

""" ##以key,value的形式增加键值对

D.setdefault(k[,d]) -> D.get(k,d), also set D[k]=d if k not in D """

pass

示例:

d = {'name':'tom','age':22,'hobby':'male'}

d.setdefault("work","IT")

print(d)

结果:

def update(self, E=None, **F): # known special case of dict.update

""" ##将两个字典不同的地方更新到一起

D.update([E, ]**F) -> None. Update D from dict/iterable E and F.

If E is present and has a .keys() method, then does: for k in E: D[k] = E[k]

If E is present and lacks a .keys() method, then does: for k, v in E: D[k] = v

In either case, this is followed by: for k in F: D[k] = F[k]

"""

pass

示例:

d = {'name':'tom','age':22,'hobby':'male'}

d1 = {'name':'tony',"work":'Teacher'}

d.update(d1)

print(d)

结果:

def get(self, k, d=None): # real signature unknown; restored from __doc__

""" ##通过key取value

D.get(k[,d]) -> D[k] if k in D, else d. d defaults to None. """

pass

def values(self): # real signature unknown; restored from __doc__

""" ##取字典的value

D.values() -> an object providing a view on D's values """

pass

示例:

d = {'name':'tom','age':22,'hobby':'male'}

d2 = d.values()

print(d2)

结果:

def items(self): # real signature unknown; restored from __doc__

""" ##以对应的方式取key和value

D.items() -> a set-like object providing a view on D's items """

pass

示例:

d = {'name':'tom','age':22,'hobby':'male'}

for k,v in d.items():

print(k,v)

结果:

def keys(self): # real signature unknown; restored from __doc__

""" ##只去字典的key

D.keys() -> a set-like object providing a view on D's keys """

pass

示例:

d = {'name':'tom','age':22,'hobby':'male'}

d3 = d.keys()

print(d3)

结果:

def copy(self): # real signature unknown; restored from __doc__

""" D.copy() -> a shallow copy of D """

pass

@staticmethod # known case

def fromkeys(*args, **kwargs): # real signature unknown

""" Returns a new dict with keys from iterable and values equal to value. """

pass

示例:

d4 = dict.fromkeys("height",[177])

print(d4)

结果:

元组解析:(元组又叫不可变列表)

def count(self, value): # real signature unknown; restored from __doc__

""" ##计算每个元素出现的次数

T.count(value) -> integer -- return number of occurrences of value """

return 0

示例:

tu = ("name","age","sex","female","male")

tu1 = tu.count("sex")

print(tu1)

结果:

def index(self, value, start=None, stop=None): # real signature unknown; restored from __doc__

""" ##根据元素去索引值,可以指定开始和结束

T.index(value, [start, [stop]]) -> integer -- return first index of value.

Raises ValueError if the value is not present.

"""

return 0

示例:

tu = ("name","age","sex","female","male")

tu2 = tu.index("female")

print(tu2)

结果:

补充:range和len

range的用法: 取一个范围内的数字

示例:

for i in range(10):

print(i)

结果:

len的用法:取一个数据类型的长度

示例:

d = {'name':'tom','age':22,'hobby':'male'}

print(len(d))

结果:

range结合len的使用:

l1 = [1, 2, 'alex', ['WuSir', 'taibai', 99], 6]

for i in range(len(l1)):

print(i,",",l1[i])

结果:

小练习题:

l1 = [1, 2, 'alex', ['WuSir', 'taibai', 99], 6]

# 将alex的首字母大写

l1[2] = l1[2].capitalize()

print(l1)

结果:

#将 'WuSir'全部变成大写

l1[3][0] = l1[3][0].upper()

print(l1)

结果:

#将99变成字符串100

l2 = l1[3][2] + 1

l1[3][2] = str(l2)

print(l1)

结果:

dic = {'name_list':['高猛', '于其',],

1:{

'alex': '李杰',

'high': '175',

}

}

#['高猛', '于其',],在里面增加一个元素‘wusir’

dic["name_list"].append("wusir")

print(dic)

结果:

l1 = [11, 22, 33, 44, 55]

#删除索引为奇数的元素

for i in range(len(l1)-1,-1,-1):

if i % 2 == 1:

del l1[i]

print(l1)

结果:

dic = {'k1': 'v1', 'k2': 'v2', 'k3':'v3', 'name':'alex'}

#删除key里面含有k字符的键值对

l = []

for i in dic:

l.append(i)

for n in l:

if 'k' in n:

dic.pop(n)

print(dic)

结果:

1、格式化输出%s和%d:

name = input('请输入名字:')

age = input('请输入年龄:')

job = input('请输入职业:')

hobby = input('请输入爱好:')

msg = '''------------ info of %s -----------

Name : %s

Age : %d

job : %s

Hobby: %s

------------- end -----------------

''' % (name, name, int(age), job, hobby)

print(msg)

结果:

# 购物车

# 功能要求:

# 要求用户输入总资产,例如:2000

# 显示商品列表,让用户根据序号选择商品,加入购物车

# 购买,如果商品总额大于总资产,提示账户余额不足,否则,购买成功。

goods = [{"name": "电脑", "price": 1999},

{"name": "鼠标", "price": 10},

{"name": "游艇", "price": 20},

{"name": "美女", "price": 998},

]

for i in range(len(goods)):

print(i,",",goods[i])

shop_c = []

money = int(input("请输入购物金额:").strip())

while True:

print(("如果退出请按'q'").center(30, "-"))

choice = input('请选择商品编号:').strip()

if choice == 'q':

s = ",".join(shop_c)

print("您最终选择的商品有%s"%s)

break

else:

choice = int(choice)

if choice >= len(goods):

print('没有此选项,请重新输入')

continue

shop_c.append(goods[choice]['name'])

money -= goods[choice]['price']

print("您选择的产品有%s"%(shop_c),"共计%s样商品"%(len(shop_c)),"剩余金额为:%s元"%(money))

if money < goods[choice]['price']:

print("您的余额不足以购买%s"%(goods[choice]['name']),"剩余%s元"%(money),"请充值...")

recharge = int(input("充值金额为:").strip())

money += recharge

print("充值后当前金额为%s"%(money))

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值