【Python】数据类型

数字

●整型( int)123

●浮点型(float)3.14

●布尔型(bool) True/False

序列

字符串

字符串拼接

​    打印字符串,可以用+拼接,也可以使用,拼接

print("Hello World")
print("Hello" + "World")
print("Hello" "World")
print("Hello", "World")
print("Hello" * 5)

#-*- coding:utf-8 -*- 在文件头部加上这行注释防止出现中文乱码

#-*- coding:utf-8 -*-

a = "Hello"
print(a)

变量与字符串的拼接

​        支持多种变量与字符串的拼接

a = "Hello"
b = "World"
print(a)
print("{} World".format(a))
print(f"{a} World")
print("Python " + a + " World")
print("%s" % a)
print("%s % s" % (a,b))

转义字符"\": \n \t \' \" \\

取消转义字符r"..."

print(r"D:\new.txt")

字符串常用方法

a = "Hello World"
b = "World"
print(a.split('l'))  # 用l分割
print('-'.join(a))  # 用-连接每个字母
print(a.find('l'))  # 找第一个l的下标位置
print(a.find('lo'))
print(a.find('l',3,5))  # 从下标3-5找有多少个l
print(a.count('l'))  # 查l的个数
print(a.replace('l','t'))  # 用t替换l
print(a.lower())  # 变为小写
print(a.upper())  # 变为大写

print("123".isdigit())  # 字符是否都是数字
print("abc".isalpha())  # 字符是否都是字母
print("Abc".islower())  # 字符是否都是小写
print("abc".isupper())  # 字符是否都是大写
print(a.replace("l","n",1))  # 替换字符串,第三个参数代表替换前n个

例题:

连接字符串

print(input() + input())

将字符串转换成小写字母

print(input().lower())

列表

list1 = [1,5,6]
print(list1)

list2 = ["Hello", "World"]
print(list2)

列表中支持多种类型

list3 = [1, "hello", 1.23,True,[ "world", 1]]
print (list3)

访问列表中的值,通过索引访问
(索引可以是负数,-1代表最后一位)

list1 = [1,5,8,7]
print(list1[0], list1[1])
# print(list1[4])  越界了
print(list1[-1])

索引的范围:-n ~ n-1

例题:

分别打印list3中的hello和world ?

list3 = [1, "hello", 1.23,True,[ "world", 1]]
print (list3[1])
print (list3[4][0])

添加、插入、删除

list1 = [1,5,6,'Hello',['Hello', 'World']]
print(list1[-1][0])

list1.append(5)
print(list1)

list1.insert(3, 'World')
print(list1)

list1.pop(2)
print(list1)

list1 = [1,2,3]
list2 = [4,5,6]
list1.extend(list2)
print(list1)

list1 = [1,5,7,8]
list2 = [2,6]
# 扩展
list1 = list1 + list2
print(list1)
list1.extend(list2)
print(list1)
# 删除
list1.remove(5)
print(list1)
del list1[1]
print(list1)
del list1
# print(list1)
# 清空
# list1.clear()
# print(list1)

列表截取,左闭右开,list1[:i] + list1[i:] == list1

list1 = [1,2,3]
list2 = [4,5,6]
list1.extend(list2)
print(list1[1:3])
print(list1[:-1])
print(list1[1:])
print(list1[1:4:2])

字符串截取?

a = "Hello"
print(a[1:4:2])

遍历列表

list1 = [1,5,8,7]

for item in list1:
    print(item)

# 循环时获取下标
for i,item in enumerate(list1):
    print(i, item)

排序、逆序、反向

list1 = [1,5,8,7]
# 正序
list1.sort()
print(list1)
# 逆序
list1.sort(reverse=True)
print(list1)
# 反向
list1.reverse()
print(list1)

列表复制

list1 = [1,2,3,4,5,6,[1,2]]

# 直接赋值:对象的引用
list2 = list1

# 浅拷贝:拷贝对象,但不会拷贝对象内部的子对象
list2 = list1.copy()

# 深拷贝:完全拷贝对象及其子对象
import copy
list2 = copy.deepcopy(list1)
print(list2)
list1[6][0] = 10
print(list2)

直接赋值:对象的引用

浅拷贝:拷贝对象,不会拷贝对象内部的子对象

深拷贝:完全拷贝对象及其子对象

字符串转列表

str1 = "hello"
print(list(str1))

列表转字符串

list1 =[ "h","e","l","l","o"]
print ("".join(list1))
str1 = "hello"
print("-".join(str1))

str1 = "helloworld"
list1 = list(str1)
print(list1)

list1 = ['h','e','l','l','o']
# str1 = str(list1)
print(str1)
str1 = "".join(str1)

换行输出字符串单词

n = input()
print(n.replace(' ','\n'))
print("\n".join(input().split()))

判断字符串是否回文("abcba")

str1 = input()
if str1 == str1[::-1]:
    print(1)
else:
    print(0)
str1 = input()
print(int(str1 == str1[::-1]))

序列函数

●`len()`长度

●`'c' in str`判断元素'c'是否在`str `序列中.

●max() min()最大值最小值

●count()元素出现次数

●index(x,i,j)查找指定元素的索引(第一个),i和j代表查找的索引范围

list1 = [1,2,3,4]
str1 = "Hello"
print(len(list1), len(str1))
print(1 in list1, "h" not in str1)
print(max(list1), min(str1))
print(list1.count(5), str1.count("l") )
print(list1.index(3), str1.index("l") )
print(list1.index(3,2,3))

元组

元组和列表类似,区别是元组一旦初始化就不能修改
只有1个元素时,加逗号,为了和数学公式中的小括号区分

tuple1 = (1)
print(tuple1)
tuple2 = (1,)
print(tuple2)
tuple3 = (1,5)
print(tuple3)

是否能替换值?

tuple1 = (1,5)
print(tuple1[0])
# tuple1[0] = 1
# print(tuple1[0])

tuple2 = (1,5,[2,4])
# tuple2[2][0]= l
# tuple2[2]= [1,4]
print(tuple2)

list1 = [2,4]
tuple3 = (1,5,list1)
# tuple3 = (1,5, listl.copy () )
list1[0] = 1
print (tuple3)

字典和集合

字典dict

映射类型{key:value}

dict1 = {
    "name":"zhangsan",
    "age":18,
}

dict1["name1"] = 20

for k,v in dict1.items():
    print(k + ":" + str(v))

dict1.update({'name2' : 'wangwu',"age2":20})
print(dict1)
del dict1['name2']
print(dict1)

获取字典中的元素

1.通过key

dict1 = {
    "name":"zhangsan",
    "age":20,
}
print(dict1["name"], dict1["age"])
dict1["age"] = 18  # 修改
print(dict1)

2.通过get方法(如果没有对应值,会输出None,不会报错,后面可以加默认值)

dict1 = {
    "name":"zhangsan",
    "age":20,
}
print(dict1.get("name"))
print(dict1.get("name1", "jack"))

遍历

dict1 = {
    "name":"zhangsan",
    "age":18,
}

for k in dict1:
    print(k)

for k,v in dict1.items():
    print(k,":",v)

print(dict1.keys())
print(dict1.values())

赋值、添加、删除、更新

dict1 = {
    "name":"zhangsan",
    "age":18,
}

dict1["name1"] = 20  # 添加一个name1
dict1.update({'name2' : 'wangwu',"age2":20})  # 更新一个name2
print(dict1)
del dict1['name2']  # 删除一个name2
print(dict1)

例题:

list = input().split()
dict = {}
for item in list:
    dict[item] = list.count(item)
print(dict)
list = input().split()
print({item: list.count(item) for item in list})

phone_dict = {
    'zhangsan': '13300110011',
    'lisi': '15511223344',
    'luo': '17745456767',
    'lihua': '18877668899',
    'jack': '16645674567'
}

while True:
    name = input('\n请输入名字:')
    if name in phone_dict:
        print(phone_dict[name])
    else:
        print('该联系人不存在')
        
    # number = input('\n请输入电话号码:')
    # if number in phone_dict:
    #     print(phone_dict[number])
    # else:
    #     print('该号码不存在')

集合set

—组key的集合,key不重复

集合是一个无序且无索引的集合,没有重复的元素。集合是Python中可用的四种内置数据类型之一,使用大括号编写。鉴于集合是无序的,不可能对集合的值进行排序。

set1 = {"name", "height", "height"}
print(set1)
set1.add("weight")
print(set1)
set1.remove("height")
print(set1)

  • 22
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值