Python_基础_Day_1

本文详细介绍了Python编程语言的基础知识,包括变量、标准数据类型如数字、字符串、列表等的使用方法及常见内置函数,适合初学者入门。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一、变量

  由字母、数字和下划线组成且不能以数字开头

二、标准数据类型

  五种类型:数字(Numbers)、字符串(String)、列表(List)、元组(Tuple)、字典(Dictionary)

三、数字类型

  1、四种类型:int(整型)、long(长整型)、float(浮点型)、complex(复数)

  2、基本模块:math模块、cmath模块

四、字符串类型

  1、字符串类型不可变(不能修改)

  2、字符串运算符

a = 'hello'
b = 'world'

print(a + b)  # helloworld,字符串连接
print(a * 2)  # hellohello,重复输出字符串
print(a[0:3]) # hel,截取,取头不取尾

  3、内置函数

  S.capitalize():把字符串的第一个字母转为大写

  S.casefold():把字符串的第一个字母转为小写

  S.center(width[, fillchar]):返回一个宽度为width,参数为fillchar(默认为空)的居中字符串

  S.count(sub, start=None, end=None):在start和end范围中查找子串sub在S中的数量

  S.encode(encoding='utf-8', errors='strict'):默认返回一个utf-8编码的字符串

  S.startswith(self, prefix, start=None, end=None):在start和end范围中检查字符串S是否以prefix开头,是返回True,不是返回False

  S.endswith(self, suffix, start=None, end=None):在start和end范围中检查字符串S是否以suffix结尾,是返回True,不是返回False

  S.expandtabs(tabsize=8):把字符串中的 tab 符号('\t')转为空格

  S.find(sub, start=None, end=None):从左向右在start和end范围中检查子串sub是否在S中,在则返回起始索引值,不在则返回-1

  S.rfind(sub, start=None, end=None):从右向左查找

  S.index(sub, start=None, end=None):从左向右在start和end范围中检查子串sub是否在S中,在则返回起始索引值,不在报错

  S.rindex(sub, start=None, end=None):从右向左查找

  S.format(*args, **kwargs):格式化输出

  S.format_map(mapping)

  S.join(iterable)::把iterable序列中的元素用指定的S字符连接成一个新的字符串

  S.ljust(width[, fillchar]):以指定的宽度左对齐显示,默认以空格填补,宽度小于字符串的长度则显示原字符串

  S.rjust(width[, fillchar]):以指定的宽度右对齐显示,默认以空格填补,宽度小于字符串的长度则显示原字符串  

  S.replace(old, new[, count]):把字符串S中的old字符替换成new字符,如果没有指定count则全替换,否则按count数值来确定替换次数

  S.split(sep=None, maxsplit=-1):通过字符sep分割字符串返回一个列表,sep默认为空,maxsplit确定分割次数

  S.rsplit(sep=None, maxsplit=-1):从右向左分割

  S.splitlines([keepends]):按行分割

  S.strip([chars]):去除字符串str前后参数chars(默认为空格),返回去除后的新字符串

  S.lstrip([chars]):去除左边

  S.rstrip([chars]):去除右边

a = 'hello'
b = 'world'
c = 'Abc'

# 1、capitalize、casefold
print(a.capitalize()) # Hello
print(a) # hello
print(c.casefold()) # abc
print(c) # Abc

# 2、center
print(a.center(10))  #   hello
print(a.center(10,'*')) # **hello***

# 3、count
print(a.count('l')) # 2
print(a.count('l',0,3)) # 1

# 4、encode
print(a.encode()) # b'hello'

# 5、startswith、endswith
print(a.startswith('h')) # True
print(a.startswith('a')) # False
print(a.endswith('o')) # True
print(a.endswith('c')) # False

# 6、expandtabs
print('a\tb'.expandtabs()) # a       b

# 7、find、index、rfind、rindex
print(a.find('a')) # -1
print(a.find('h')) # 0
print(a.rfind('h')) # 0
print(a.index('h')) # 0
#print(a.index('a')) # ValueError: substring not found

# 8、join
print('-'.join(['a','b','c'])) # a-b-c

# 9、rjust、ljust
print(a.ljust(10)) # hello
print(a.rjust(10)) #     hello

# 10、replace
print(a.replace('l','e')) # heeeo

# 11、split、rsplit、splitlines
print(a.split('e')) # ['h', 'llo']
print('a\nb'.splitlines()) # ['a', 'b']

# 12、strip、lstrip、rstrip
print(' a  '.strip()) # a
print(' a '.lstrip()) # a
print(' a '.rstrip()) #  a

  S.swapcase():大小写转换,大写换小写,小写转大写

str1 = "abc"
str2 = "ABC"
print(str1.swapcase()) #ABC
print(str2.swapcase()) #abc

  S.title():转为标题

  S.lower():转为小写

  S.upper():转为大写

s = 'hello world'

print(s.title()) # Hello World
print(s.upper()) # HELLO WORLD
print(s.lower()) # hello world

  S.isalnum():如果字符串至少有一个字符并且所有字符都是字母或数字则返回True,否则返回 False

s1 = "abcdef1"
s2 = "b c"
s3 = ""
print(s1.isalnum()) #True
print(s2.isalnum()) #False
print(s3.isalnum()) #Fals

  S.isnumeric():与str.isnum功能相同

  S.isalpha():检测字符串是否只有字母,是则返回True,否则返回False

s1 = "abc"
s2 = "a@c"
print(s1.isalpha()) #True
print(s2.isalpha()) #False

    S.isdecimal()

  S.isdigit():检测字符串是否只有数字,是则返回True,否则返回False

s1 = "123"
s2 = "a@c"
print(s1.isdigit()) #True
print(s2.isdigit()) #False

  S.isidentifier()

  S.islower(self):字符串至少包含一个区分大小写的字符且都为小写,则返回True,否则返回False

s1 = "123"
s2 = "a@c"
s3 = "a1c"
print(s1.islower()) #False
print(s2.islower()) #True
print(s3.islower()) #True 

  S.isprintable()

  S.isspace():检测字符串是否只有空格,是则返回True,否则返回False

s1 = " 3"
s2 = " "
print(s1.isspace()) #False
print(s2.isspace()) #True

  S.istitle():字符串中所有首字母大写则返回True,否则返回False

s1 = "And so On"
s2 = "And So On"
print(s1.istitle()) #False
print(s2.istitle()) #True

  S.isupper():字符串至少包含一个区分大小写的字符且都为大写,则返回True,否则返回False

s1 = "Ab"
s2 = "A1@"
print(s1.isupper()) #False
print(s2.isupper()) #True 

  max(S):返回最大字符串

  min(S):返回最小字符串

  len(S):返回字符串的长度

s = "abca"
print(max(s)) #c
print(min(s)) #a

 五、列表类型

  1、列表类型可变(能修改)

  2、列表运算符

# 1、创建列表
l = [1,2,3,4]

# 2、取元素
print(l[0]) # 1
print(l[0:3]) # [1,2,3],取头不取尾

# 3、修改列表元素
l[0] = 10
print(l) # [10, 2, 3, 4]

# 4、删除列表元素
del l[0]
print(l) # [2, 3, 4]

# 5、运算符操作
print([1,2] + [3,4]) # [1, 2, 3, 4]
print([1,2] * 4) # [1, 2, 1, 2, 1, 2, 1, 2]
print(3 in [1,2,3]) # True

  3、内置函数和方法 

  L.append(object):末尾追加

  L.extend(iterable):末尾追加

  L.clear():清除

  L.copy() :浅拷贝

  L.count(value) :返回value值的个数

  L.index(value, [start, [stop]]):在start和stop范围中查找value值,存在返回索引值,不存在就报错

  L.insert(index, object):指定位置插入值

  L.pop([index]):按索引删除值,默认删除最后一个,并返回删除的值

  L.remove(value) :按值删除

  L.reverse():反转

  L.sort(key=None, reverse=False):排序

  len(L):列表长度

  max(L):列表最大值

  min(L):列表最小值

l = [1,2,3,4]
s = [5,6,7]

# append、extend
l.append(s)
print(l) # [1, 2, 3, 4, [5, 6, 7]]
l.extend(s)
print(l) # [1, 2, 3, 4, 5, 6, 7]

#append和extend都仅只可以接收一个参数

 #append 任意,甚至是tuple

 #extend 只能是一个列表

 

# clear
#l.clear()
print(l) # []

# copy
# count
print(s.count(1)) # 0

# index
print(l.index(1)) # 0
#print(l.index(10)) # ValueError: 10 is not in list

# insert
s.insert(0,10)
print(s) # [10, 5, 6, 7]

# pop、remove
print(s.pop()) # 7
print(s) # [10, 5, 6]
print(s.pop(0)) # 10
print(s) # [5, 6]
s.remove(5)
print(s) # [6]

l = [1,2,3,4]
# reverse
l.reverse()
print(l) #[4, 3, 2, 1]

# sort
l.sort()
print(l) # [1, 2, 3, 4]

# len、max、min
print(len(l)) # 4
print(max(l)) # 4
print(min(l)) # 1

 

六、元组类型

  1、元组类型不可变(不能修改),但元组的元素的元素可变

  2、元组运算符

t = (1,2,3)
s = (2,3,4)
print(t + s) # (1, 2, 3, 2, 3, 4)
print(t[0]) # 1
print(s * 2) # (2, 3, 4, 2, 3, 4)
print(3 in s) # True

 

  3、函数与方法

  T.count(value):查找value的个数

  T.index(value, [start, [stop]]):在start和stop范围中查value值,找到则返回索引值,没找到就报错

    len(T):长度

      max(T):最大值

      min(T):最小值

l = (1,2,3,4)

# count
print(l.count(1)) # 1

# index
print(l.index(1)) # 0
print(l.index(0)) #ValueError: tuple.index(x): x not in tuple

# len、max、min
print(len(l)) # 4
print(max(l)) # 4
print(min(l)) # 1

 

七、字典类型

  1、字典类型可变

  2、字典运算

# 定义字典
d = {'a':1, 'b':2, 'c':3}

# 访问字典值
print(d['a']) # 1

# 修改字典值
d['a'] = 4
print(d) # {'a': 4, 'b': 2, 'c': 3}

  3、函数

  D.clear():清除字典

  D.copy():拷贝字典  

  D.get(k[,d]):返回指定键的值,不存在默认返回None

  fromkeys(*args, **kwargs): 

  D.items():返回所有的键值对

  D.keys():返回所有的键

  D.values():返回所有的值

  D.pop(k[,d]):删除指定的值

  D.popitem() :随机删除一个键值对

  D.setdefault(k[,d])

  D.update([E, ]**F)

d = {'a':1, 'b':2, 'c':3}

# clear
# copy(self)
#get(self, k, d=None)
print(d.get('a')) # 1

#items(self)
for i in d.items():
    print(i)
# keys(self): for i in d.keys(): print(i) #values(self) for v in d.values(): print(v)
#pop(self, k, d=None) print(d.pop('a')) print(d) #popitem(self): print(d.popitem()) #setdefault(self, k, d=None): # update(self, E=None, **F)

 八、集合类型

  set无序且不重复

转载于:https://www.cnblogs.com/jp-mao/p/9007613.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值