Python 基础

字符串

1、大小写替换
content = "hello world!"

#首字母大写
# title(self)
print(content.title()) # Hello World!

#全部大写
# upper(self)
print(content.upper()) # HELLO WORLD!

#全部小写
# lower(self)
print(content.lower()) # hello world!

#仅第一个字符串大写
# capitalize(self)
print(content.capitalize()) # Hello world!

#大小写互换
# swapcase(self)
print(content.swapcase()) # HELLO WORLD!
View Code
2、剔除空格
delete_space = "\tHello World! "

#删除两边空格
# strip(self,chars)
print(delete_space.strip()) # Hello World!

#删除左边空格
# lstrip(self,chars)
print(delete_space.lstrip()) # Hello World!

#删除右边空格
# rstrip(self,chars)
print(delete_space.rstrip()) #      Hello World!
View Code
3、查找
data = "Hello world!"
#从前面查找
# find(self,sub,__start,__end)
print(data.find("d")) # 10

# index(self,sub,__start,__end)
print(data.index("d")) # 10

#从后面查找
# rfind(self,sub,__start,__end)
print(data.rfind("l")) # 9

# rindex(self,sub,__start,__end)
print(data.rindex("l")) # 9
# 注:find跟index用法一样,但index找不到会报错,而find会输出 -1
View Code
4、替换,切割
"""替换"""
content = "Heiio World!"
# replace(self,old,new,count)
print(content.replace("i","l")) #Hello World!


"""切割"""
content = "Hello World !"
# split(self,sep,maxsplit)
content  = (content.split(' '))
print(content) # ['Hello', 'World', '!']
View Code
5、填充
fill =  "Hello"

#固定左面,字符不足时,填充
# ljust(self,width,fillchar)
print(fill.ljust(10,"-")) # Hello-----

#固定右面,字符不足时,填充
# rjust(self,width,fillchar)
print(fill.rjust(10,"-")) # -----Hello

#固定右中,字符不足时,填充
# center(self,width,fillchar)
print(fill.center(10,"-")) # --Hello---

#固定右面,字符不足时,补0
# zfill(self,width)
print(fill.zfill(10)) # 00000Hello
View Code
6、is判断
#是否仅由空格
# isspace(self)
judge = "   "
print(judge.isspace()) # True
judge = ""
print(judge.isspace()) # False
judge = "Hello world"
print(judge.isspace()) # False


#像不像数字
# isdigit(self)
judge = "1"
print(judge.isdigit()) # True
judge = "s1"
print(judge.isdigit()) # False
judge = " 1 2 3"
print(judge.isdigit()) # False


#是否仅由字母或数字
# isalnum(self)
judge = "s1"
print(judge.isalnum()) # True
judge = "Hello world"
print(judge.isalnum()) # False


#是否仅由字母组成
# isalpha()
judge = "Hello"
print(judge.isalpha()) # True
judge = "Hello world"
print(judge.isalpha()) # False
judge = "Hello,world"
print(judge.isalpha()) # False


#是否只包含十进制字符
# isdecimal(self)
judge = "a"
print(judge.isdecimal()) # False
judge = "123432"
print(judge.isdecimal()) # True


#判断变量名是否合法
# isidentifier(self)
judge = "1_a"
print(judge.isidentifier()) # False
judge = "asdf"
print(judge.isidentifier()) # True


#是否仅由数字组成
# isnumeric(self)
judge = "1_one"
print(judge.isnumeric()) # False
judge = "123"
print(judge.isnumeric()) # True


#是否都是可打印字符(in repr())或字符串为空
# isprintable(self) 
judge = ""
print(judge.isprintable()) # True
judge = "Hello world!"
print(judge.isprintable()) # True


#首字母大写
# istitle(self)
judge = "Hello world"
print(judge.istitle()) # False
judge = "Hello World "
print(judge.istitle()) # True
judge = "Hello World !"
print(judge.istitle()) # True


#字母小写
# islower(self)
judge = "Hello world"
print(judge.islower()) # False
judge = "hello world"
print(judge.islower()) # True


#字母大写
# isupper(self)
judge = "HEllo World"
print(judge.isupper()) # False
judge = "HELLO WOELD"
print(judge.isupper()) # True
View Code
7、其他判断
# 判断尾
# endswith(self,suffix,start,end)
letter = "Hello World"
print(letter.endswith("d")) # True
print(letter.endswith("l")) # False



# 判断首
# startswith(self,prefix,start,end)
letter = "Hello World"
print(letter.startswith("h")) # False
print(letter.startswith("H")) # True
View Code
8、join
# 字符串join
letter = "hello"
letter = "!".join(letter)
print(letter)


# 列表join
list_join = ["Hello","World"]
list_join = "||".join(list_join)
print(list_join)


# 元祖join
tuple_join = ["Hello","World"]
tuple_join = " + ".join(tuple_join)
print(tuple_join)
View Code
9、格式化
'''
字符串   %s
整数     %d
浮点数   %f
format  {} #接受多种类型
'''


content_s = "Hello %s" %"world"
print(content_s) # Hello world



content_d = "1+1 = %d" % 2
print(content_d) # 1+1 = 2



content_f = "0.1 + 1 = %f" % 1.1
print(content_f) # 0.1 + 1 = 1.100000



# 使用format(self,args,kwargs)
# *args     任意数量的形参
# **kwargs  任意数量的实参(关键字实参)
content_format = "Hello world {}".format("!")
print(content_format) # Hello world !
students = "{name} is  {year} years old {}" .format("!",name="Tom",year=16)
print(students) # Tom is  16 years old !


# 使用 format_map(self,map)
content_format_map = "It's a {color} {animal}"
map_dict = {"color":"green","animal":"kitty"}
new_content = content_format_map.format_map(map_dict)
print(new_content) # It's a green kitty
View Code
10、其他操作
#返回使用空格展开所有制表符的S的副本
# expandtabs(self,tabsize)
expand = "Hello\tWorld"
print(expand.expandtabs(10)) # Hello     World
View Code

 

translate 转换

s = "Hello \nWorld"
d = dict.fromkeys(range(32))

result = s.translate(d)
print(result)
View Code
s = "Hello \nWorld"
d = str.maketrans("HW","hw")
result = s.translate(d)
print(result)
View Code

 

 

列表

1、切片 顾头不顾尾
列表的索引值: 0
animal = ["dog","cat","pig","tiger","panda"]
#取索引为0的值
print(animal[0]) # dog

#从索引第一个到倒数第二个
print(animal[1:-3]) # ['cat', 'pig']

#从索引第一个到最后一个
print(animal[1:]) # ['cat', 'pig', 'tiger', 'panda']

#复制列表并步进
print(animal[::2]) # ['dog', 'pig', 'panda']
View Code
2、修改,添加,删除
#   修改
animal = ["dog","cat","pig","tiger","panda"]
#单个修改
animal[0] = "wolf"
print(animal) # ['wolf', 'cat', 'pig', 'tiger', 'panda']

#多个修改
animal[0:2] = ["dogs","cats"] # ['dogs', 'cats', 'pig', 'tiger', 'panda']
print(animal)



#   添加
# append(self,object)
animal = ["dog","cat","pig","tiger","panda"]
animal.append("wolf")
print(animal) # ['dog', 'cat', 'pig', 'tiger', 'panda', 'wolf']

# insert(self,index,object)
animal = ["dog","cat","pig","tiger","panda"]
animal.insert(-1,"wolf")
print(animal) # ['dog', 'cat', 'pig', 'tiger', 'wolf', 'panda']



#   删除
# remove(self,object)
animal = ['dog', 'cat', 'pig', 'tiger', 'wolf', 'panda']
animal.remove("wolf")
print(animal) # ['dog', 'cat', 'pig', 'tiger', 'panda']

# pop(self,index)
animal = ['dog', 'cat', 'pig', 'tiger', 'wolf', 'panda']
pop_animal = animal.pop(-2)
print(animal) # ['dog', 'cat', 'pig', 'tiger', 'panda']
#查看删除了那个元素
print(pop_animal) # wolf

# del
animal = ['dog', 'cat', 'pig', 'tiger', 'wolf', 'panda']
del animal[-2]
print(animal) # ['dog', 'cat', 'pig', 'tiger', 'panda']
#删除整个列表
del animal
print(animal) # 报错(NameError: name 'animal' is not defined)



#清空列表
# clear(self)
animal = ['dog', 'cat', 'pig', 'tiger', 'wolf', 'panda']
animal.clear()
print(animal) # []
View Code
3、for循环
# range(start,end,step)

number_list_1 = []
for i in range(5):
    number_list_1.append(i)
print(number_list_1) # [0, 1, 2, 3, 4]

# 0—10的偶数
number_list_2 = []
for i in range(0,11,2):
    number_list_2.append(i)
print(number_list_2) # [0, 2, 4, 6, 8, 10]

# 1—10的平方
#第一种
number_list_3 = []
for i in range(1,11):
    square = i ** 2
    number_list_3.append(square)
print(number_list_3) # [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

#第二种
square = [i**2 for i in range(1,11)]
print(square) # [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
View Code
4、拷贝
a = [[1,2],3,4]
b = a.copy() # 与 a[:]的作用一样
# 整数修改
b[1] = "three"
print(a)
print(b)
# a完全不受b的影响



a = [[1,2],3,4]
b = a.copy()
# 列表修改
b[0][1] = "two"
print(a)
print(b)
# a受到b的影响,改变了值
View Code

下面解释图,来源网络

5、其他操作
#计算某元素出现的次数
# count(self,object)
animal = ["dogs"]
for i in range(5):
    animal.append("dog")
count_dog = animal.count("dog")
print(count_dog) # 5



# 将一个列表,延伸到,另外一个列表
# extend(self,iterable)
content_1 = [1,2,3]
content_2 = [1,4,5]
#将 content_1 延伸到 content_2 里面
content_2.extend(content_1)
print(content_1) # [1, 2, 3]
print(content_2) # [1, 4, 5, 1, 2, 3]



#查看元素的索引
# index(self,object,start=0,end)
animal = ["dog","cat","pig","tiger","panda"]
index = animal.index("pig")
print(index) # 2



#对列表排序
#永久性
# sort(self,key,reverse)
animal = ["dog","cat","pig","tiger","panda"]
animal.sort()
print(animal) # ['cat', 'dog', 'panda', 'pig', 'tiger']
# reverse 字母相反顺序
animal.sort(reverse=True)
print(animal) # ['tiger', 'pig', 'panda', 'dog', 'cat']

#临时性
animal = sorted(animal) # ['cat', 'dog', 'panda', 'pig', 'tiger']
print(animal)
# reverse(self) 只是按照列表倒着打印
animal.reverse() # ['tiger', 'pig', 'panda', 'dog', 'cat']
print(animal)
View Code

 

 

 

元祖

元祖只能查,而不能修改

tuple_directory = (1,2,3)
#查找
# index(self,x)
print(tuple_directory.index(1)) # 0

#计算某个值出现的次数
# count(self,x)
print(tuple_directory.count(1)) # 1

#
print(tuple_directory[2]) # 3
print(tuple_directory[:]) # (1, 2, 3)
for i in enumerate(tuple_directory):
    print(i)
"""(0, 1)
   (1, 2)
   (2, 3)
"""
View Code

 

集合

 集合特点:

确定性(去重)

无序性

互异性

 

集合分类:可变集合、不可变集合

可变集合(set):可添加和删除元素,非可哈希的,不能用作字典的键,也不能做其他集合的元素

不可变集合(frozenset):可哈希的

 

集合用法

class_1 = set(["小明","小军","小李"])
class_2 = set(["小明","小红","小智"])

# 交集 (&)
intersection = class_1.intersection(class_2)
print(intersection) # {'小明'}



# 并集 (|)
union = class_1.union(class_2)
print(union) # {'小明', '小李', '小军', '小智', '小红'}



# 补集 (-)
difference = class_1.difference(class_2)
print(difference) # {'小军', '小李'}



# 反向交集(^)
symmetric = class_1.symmetric_difference(class_2)
print(symmetric) # {'小军', '小李', '小红', '小智'}



# 父集 (>)
superset = class_1.issuperset(class_2)
print(superset) # False


# 子集 (<)
subset = class_1.issubset(class_2)
print(subset) # False
View Code
class_1 = set(["小明","小军","小李"])
class_2 = set(["小明","小红","小智"])

# 访问
# 因为集合是无序的,所以不能通过索引,只能通过遍历或,进行判断
print("小明" in (class_1 and  class_2)) # True



# 更新

# add作为一个元素,进行添加
class_1.add("小雷")
print(class_1) # {'小军', '小明', '小雷', '小李'}


# update作为一个序列,进行添加
class_2.update("小雷")
print(class_2) # {'小红', '雷', '小智', '小', '小明'}


# remove()  删除
class_2.remove((""))
print(class_2) # print(class_2)


# clear()   清除集合的内容
class_2.clear()
print(class_2) # set()


# 删除
del class_2
View Code

 

 

字典

无序性,键唯一

 

1、查看

#查看键

person = {"name":"小明","age":16}

print(person.keys()) # dict_keys(['name', 'age'])
for key in person.keys():
    print(key)  # name
                # age



#查看值

person = {"name":"小明","age":16}
print(person.values()) # dict_values(['小明', 16])

for value in person.values():
    print(value) # 小明
                 # 16



#遍历所有的键-值对

person = {"name":"小明","age":16}
for key,value in person.items():
    print(key,'--->',value) # name ---> 小明
                            # age ---> 16
View Code

2、修改 ,set()的使用

#根据键来修改值
person = {"name":"小明","age":16}
person["age"] = 17
print(person) # {'name': '小明', 'age': 17}



#如果本身存在,不会进行修改
#setdefault(self,k,default)
person = {"name":"小明","age":16}
person.setdefault("age",17)
print(person) # {'name': '小明', 'age': 16}



#更新
#不存在时,进行扩展
# update(self,m,kwarg)
person = {"name":"小明","age":16}
new_person = {"sex":""}
person.update(new_person)
print(person) # {'name': '小明', 'age': 16, 'sex': '男'}

#存在时,进行更新
person = {"name":"小明","age":16}
new_person = {"name":"小李"}
person.update(new_person)
print(person) # {'name': '小李', 'age': 16}



#使用set(), 找出独一无二的元素
persons = {"student_1":"小明","student_2":"小明"}
for value in set(persons):
    print(value) # 小明
View Code

3、添加 ,zip()的使用

person = {"name":"小明","age":16}
person["sex"] = ""
print(person) # {'name': '小明', 'age': 16, 'sex': '男'}



#使用zip(),添加键值-对
students = {}
key_list = ["one","two",'three']
value_list = ["小亮","小红","小王"]
#zip(iter1,iter2...)
for key,value in zip(value_list):
    students[key] = value
print(students)
View Code

4、删除

#使用del删除
person = {'name': '小明', 'age': 16, 'sex': ''}
del person['sex']
print(person) # {'name': '小明', 'age': 16}



#使用pop删除
person = {'name': '小明', 'age': 16, 'sex': ''}
# pop(self,k)
pop = person.pop("sex")
print(pop) #
print(person) # {'name': '小明', 'age': 16}



#使用popitems() 随机返回并删除字典中的一对键和值
person = {'name': '小明', 'age': 16, 'sex': ''}
# popitem(self)
person.popitem()
print(person) # {'name': '小明', 'age': 16}
View Code

5、嵌套

#字典嵌套列表
students = {"name":["小明","小李","小张"],"age":[15,15,16]}
print(students)



#字典嵌套字典
students = {"小明":{
    "age":15,
    "sex":"",
}}
print(students) # {'小明': {'age': 15, 'sex': '男'}}



#字典嵌套列表和字典
students = {"name":[{"小明":{"age":15}},{"小李":{"age":15}}]}
print(students)
View Code

6、其他操作

#对所有的value做初始值
# fromkeys(seq)
students  = dict.fromkeys(["小明","小李","小张"])
print(students) # {'小明': None, '小李': None, '小张': None



# sorted(iterable,key,reverse)
students  = {2:"two",1:"one",3:"three"}
print(sorted(students)) # [1, 2, 3]
print(sorted(students,reverse=True)) # [3, 2, 1]

# 根据值进行排序
print(sorted(students.values())) # ['one', 'three', 'two']
print(sorted(students.values(),reverse=True)) # ['two', 'three', 'one']
View Code
 
 
posted @ 2019-04-19 14:20  Sun先生  Views(271)  Comments(0Edit  收藏  举报