python基础知识笔记

文章讲解了Python中的字符串操作、基本运算符、函数如input和print,以及列表、元组、字典等数据结构的使用和功能。还涉及了排序函数sorted和集合操作。
摘要由CSDN通过智能技术生成

目录

输入

输出

运算符

注释

简单函数

列表

元组

字典


输入:

input()函数将用户输入的内容当做一个字符串类型。

字符串转换

转换成整数,使用int()函数:num1 = int(str)

转换成小数,使用float()函数:f1 = float(str)

输出:

print()函数可以直接打印字符串,这是输出字符串的常用方式。

print("Hello", "World", sep="-", end="!")  
输出:Hello-World!

格式化输出:

>>>name=input("请输入一个人的名字:")

请输入一个人的名字:郭靖

>>>country=input("请输入一个国家的名字:")

请输入一个国家的名字:中国

>>>print("{}来自于{}".format(name,country))

print("%d + %d = %d" % (100,200,300))

print("%s %s" % ("world","hello"))

print函数输出数据后会换行,如果不想换行,需要指定end="":

print("hello" , end="")

print("world" , end="")

Python字符串:

>>>name="Python语言程序设计"

>>>print(name[:6])

Python

运算符

逻辑运算符:与and 、或or 、非not

位运算符:按位与& 、按位或| 、按位异或^(对应位不同结果为1)、按位取反~、左移动<< 、右移动>>

成员运算符:in 、not in

身份运算符:is 、is not

运算符优先级:

注释:

#使用多个#

#作注释

'''

用三个单引号

作注释

'''

简单函数

Sep分隔符:

a = input("")

print(*a, sep=":")

测试输入:123

预期输出:1:2:3

Join函数:

num = input()

print(" ".join(num))   输出每一位上的数字,用空格隔开

Split()函数:

>>> a="I love China"

>>> a.split()    分隔符为空,分割次数默认

['I', 'love', 'China']

>>> c="I#love#China#andyou#you"

>>> c.split("#")   使用'#'作为分隔符

['I', 'love', 'China', 'andyou', 'you']

append()函数与extend()函数:

append添加的是元素本身,而extend添加的是元素的值

append可以添加所有类型元素,而extend只能添加序列

       

list1 = ['zhangsan', 'lisi', 'wangwu']

list2 = ['zhangsan', 'lisi', 'wangwu']

list1.append([1,2,3])

print('append添加整个列表:', list1)

list2.extend([1,2,3])

print('extend添加列表的值:', list2)

append添加整个列表: ['zhangsan', 'lisi', 'wangwu', [1, 2, 3]]

extend添加列表的值: ['zhangsan', 'lisi', 'wangwu', 1, 2, 3]

                

解包:

Set()函数:

删除重复值(返回的集合对象是无序的)

x = set('eleven')

y = set('twelve')

print(x,y)

{'e', 'n', 'v', 'l'} {'e', 'v', 'l', 'w', 't'}

Sorted()函数

sorted(iterable,key=None, reverse=False)

iterable:可迭代对象

key:通过这个参数可以自定义排序逻辑

reverse:指定排序规则,True为降序,False为升序(默认)。

这篇文章写得很好

Python中的排序函数--sorted()函数-CSDN博客

列表:

创建

ls1=[]                创建空列表ls1

ls2=list(range(n))    使用range(n)生成整数序列并转换成列表ls2

打印

(3)逆序打印列表3

print(ls3[ :  : -1])

内置函数:append(obj)追加元素;insert(index,obj)插入;del 方法和 pop(index)删除;reverse():反向排列;remove():移除;sort():列表排序(元素类型必须全部为字符串或者全部为整型和浮点型);count():统计某出现的次数

元组:

创建

menu1 = ('meat','fish','chicken')

访问

print(menu[1:3])

('fish', 'chicken')

修改元组:元组不能修改

内置函数: len(tuple):计算元素个数;max(tuple):返回元素的最大值;min(tuple):返回元素的最小值;tuple(seq):将列表转换为元组;index()返回下标

操作符:加+、乘*、in

字典:

创建

# 创建并初始化menu字典

menu = {'fish':40, 'pork':30, 'potato':15, 'noodles':10}

访问

# 获取并返回menu字典中键'fish'键对应的值

print(menu['fish'])

40

添加键-值对

 向menu字典中添加菜名和价格

menu['juice'] = 12

修改

 修改menu字典中菜fish的价格

menu['fish'] = 50

删除

删除noodles键值对

del menu['noodles']

内置函数:items()方法会将字典里的所有的键与值一起返回;keys()方法,该方法会将字典里的键遍历出来;values()方法,该方法会将字典里的值遍历出来

利用items()方法遍历输出键和值

for key,value in menu.items():

    print('\nkey:'+key)

    print('value:'+value)

集合

创建

collection = {1, 2, 3, 4, 5}

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

collection = set(lists)

内置函数:添加元素add()、update();删除元素pop()、clear()、remove()、discard();查找in

字符串

合并

result_string = source_string1 + source_string2

full_name = "{} {}".format(first_name, last_name)

full_name = f"{first_name} {last_name}"

转换

# 将源字符串转换为大写并存入upper_string变量

upper_string = source_string.upper()

# 将源字符串每个词首字母转换为大写并存入title_string变量

title_string = source_string.title()

strip()方法:去除两侧指定的特定字符

hello_world = '  **The world ** is big!*    '

char_hello_world = hello_world.strip('TH *')

print(char_hello_world)

he world ** is big!

查找

source_string.find(sub_string)

替换

source_string.replace(old_string, new_string

分割

source_string.split(separator)

source_string = '1+2+3+4+5'

print(source_string.split('+'))

print(source_string.split('/'))

['1', '2', '3', '4', '5']

['1+2+3+4+5']

partition()函数

string_name.partition(separator)

str1 = "Python is simple.Python is strong."

res = str1.partition("Python")

print(res)

输出结果:

('', 'Python', ' is simple.Python is strong.')

数字与大小写字符表示

import string

string.digits 表示所有数字字符

string.ascii_lowercase 表示所有小写字母

string.ascii_uppercase 表示所有大写字母

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值