python基础知识二

时间:2021-12-24 18:40:07

一、运算符

      1、运算符需要注意的问题:运算符的执行顺序是从前到后的顺序执行。

      

if 1 == 2 or 2 > 1 and 1 == 1:
print("正确")
else:
print("错误")

      

      2、可以在字符串中使用 in

content = "朝鲜的核试验越演越烈,美国会采取什么样的措施呢"
if "" in content:
print("核试验")
else:
print("content")

 二、python数据类型

     1、整数 int

     创建

a = 123
a = int(123)

     转换

age = "18"
new_age = int(age)

     查看变量是什么类型

print(type(a))

 

      2、布尔值

       创建

a = True

b = False

        转换

bool(0)    #数字转换只有0为False,其他都为True
bool("") #字符串转换只有空为False,其他都为True

 

       3、字符串

         创建

a = "alex"
a = str("alex")

         转换

age = "alex"
new_age = str(age)

         字符串的拼接

name = "alex"
gender ="女"
new_str = name + gender
print(new_str)

         占位符

name = "我叫李杰,性别:%s,我今年%s岁"
new_str = name%()
print(new_str)

         移除空白

name = " connie "
new_name = name.strip()
new_name = name.lstrip()
new_name = name.rstrip()
print(new_name)

          分割

user_info = "alex sb123 9"
v = user_info.split(" ")
v = user_info.lsplit(" ",1)
v = user_info.rsplit(" ",1)

          索引

val = ""
v = val[0]

 

val = input(">>>")
i = 0
while i < len(val)
print(val[i])
i + =1

          切片

name = "我叫李杰,性别男,年龄18岁"
print(name[0]) #取第一个字符
print(name[0:2]) #取前三个字符
print(name[5:9]) #取第六到第十个字符
print(name[5:]) #取第六个字符到最后
print(name[5:-2]) #取第六个字符到倒数第三个
print(name[0:10:2]) #2为步长,从第一个字符到第十一个字符每两个取第一个
print(name[-2:]) #从后往前取两位

 

        4、列表

           创建

a = ["alex","猫","connie",5678]
a = list(["alex","猫","connie",5678])

 

           in判断

if "al" in a            #"al"不在a里在a[0]
pass
if "al" in a[0]
pass

     

           索引   

val = a[0]

           切片

a = ["alex","猫","connie",5678]
v = a[0:3:2]
print(v)

           追加

a = ["alex","猫","connie",5678]
a.append("daisy")
print(a)

          

           插入

a = ["alex","猫","connie",5678]
a.insert(1,"fish") #在第二个字符前面插入fish字符
print(a)

           移除

a = ["alex","猫","connie",5678]
a.remove("alex") #根据value删除,如有重复的,只能删除第一个
del a[1] #根据索引删除
print("")

            修改

a = ["alex","猫","connie",5678]
a[3] = "lady"
print("a")

            For循环

a = ["alex","猫","connie",5678]
for item in a:
print(item)
break #跳出循环
continue #跳出当前循环继续下次循环

        5、字典

 

            创建

v = {
"name":" connie"
"password":"123"
} #字典是无序的

            索引

v = {
"name":" connie"
"password":"123"
}
n = v["name"]

 

            增加或修改

v = {
"name":" connie"
"password":"123"
}

v["age"] = 19

print(v)

              删除

          

del v[''name"]

print(v)

 

              循环

 

 

v = {
"name":" connie"
"password":"123"
}

for item in v: #只输出key值
print(item)
for item in v.values(): #只输出value值
print(item)
for key,value in v.items(): #输出key值和value
print(item)