30python中列表-字典-字符串-三目运算符

好文手敲下,每天码代码~ 加油

三目运算符

a = 1
b = 2
# a+b不大于3执行后面的else语句 b-a = 1
print(a+b if a+b>3 else b-a)

一、列表

1.1列表的定义

​ 白话来讲:放数据的,啥都可以放,用[]表示或者list(),可变序列。对于c#或c中(数组),只能同类型数据。

1.2.列表的常用方法

(1).append()

append() 方法向列表末尾追加元素。

fruits = ['apple', 'banana', 'cherry']
fruits.append("orange")
print(fruits)

运行结果

['apple', 'banana', 'cherry', 'orange']

(2).clear()

clear()方法清空列表所有元素。

fruits = ['apple', 'banana', 'cherry', 'orange']
fruits.clear()
print(fruits)

运行结果如下:

[]

(3).copy()

copy()方法返回指定列表的副本(复制列表)

fruits = ['apple', 'banana', 'cherry', 'orange']
c = fruits.copy()
print(c)

运行结果如下:

['apple', 'banana', 'cherry', 'orange']

(4).count()

count()方法返回元素出现次数

fruits = ['apple', 'banana', 'cherry']
number = fruits.count("cherry")
print(number)

运行结果如下:

1

(5).extend()

extend()方法将列表元素(或任何可迭代的元素)添加到当前列表的末尾

fruits = ['apple', 'banana', 'cherry']
cars = ['Porsche', 'BMW', 'Volvo']
fruits.extend(cars)
print(fruits)

运行结果如下:

['apple', 'banana', 'cherry', 'Porsche', 'BMW', 'Volvo']

(6).index()

index()方法返回该元素最小索引值(找不到元素会报错)

fruits = ['apple', 'banana', 'cherry']
x = fruits.index("cherry")
print(x)    # 返回最小索引值

运行结果如下:

2

(7).insert()

在指定位置插入元素

fruits = ['apple', 'banana', 'cherry']
fruits.insert(1, "orange")
print(fruits)

运行结果如下:

['apple', 'orange', 'banana', 'cherry']

(8).reverse()

reverse() 方法反转元素的排序顺序

fruits = ['apple', 'banana', 'cherry']
fruits.reverse()
print(fruits)

运行结果如下:

['cherry', 'banana', 'apple']

(9).remove()

remove() 方法具有指定值的首个元素 #永久删除,无返回值

fruits = ['apple', 'banana', 'cherry']
fruits.remove("banana")
print(fruits)

运行结果如下:

['apple', 'cherry']

(10).pop()

pop() 删除指定位置的元素 ,不加索引默认最后一个 (类似 栈:先进后出) #有返回值

fruits = ['apple', 'banana', 'cherry']
fruits.pop(1)
print(fruits)

运行结果如下:

['apple', 'cherry']

(11).sort()

默认情况下,sort() 方法对列表进行升序排序

cars = ['Porsche', 'BMW', 'Volvo']   #以字母顺序ascill
cars.sort()
print(cars)

运行结果如下:

['BMW', 'Porsche', 'Volvo']

reverse=True 可将对列表进行降序排序。默认是 reverse=False

cars = ['Porsche', 'BMW', 'Volvo']
cars.sort(reverse=True)
print(cars)

运行结果如下:

['Volvo', 'Porsche', 'BMW']

二、字典

2.1.字典的定义

白话来讲,一个容器,也是放数据的,可变序列,保存的内容是以键值对(key:value)形式存放的。类似与json数据,但是json内容必须是双引号。

字典的每个键值之间用冒号:分隔,每个键值对之间用,隔开,整个字典包含在{ }中

dict = {key1:value1,key2:value2}

(1)字典的主要特征

1:通过键而不是通过索引来读取
2:字典是任意对象的无序集合
3:字典是可变的,可以随意嵌套
4:字典的键必须唯一
5:字典的键必须不可变

(2).创建字典的三种方法

# 第一种方法
dic1 = {'name':'hacker','age':'18'}
# 第二种方法
dic2 = dict(name='hacker',age='18')
# 第三种方法
dic3 = dict([('name','hacker'),('age','18')])

2.2字典常用方法

(1).clear()

clear()方法清空字典中的所有元素(返回空字典)

car = {"brand": "Porsche", "model": "911", "year": 1963}
car.clear()
print(car)

运行结果如下:

{}

(2).copy()

copy()方法返回字典的副本(复制字典)

car = {"brand": "Porsche", "model": "911", "year": 1963}
res = car.copy()
print(res)

运行结果如下:

{'brand': 'Porsche', 'model': '911', 'year': 1963}

(3).get()

get()方法返回指定键的值

car = {"brand": "Porsche", "model": "911", "year": 1963}
x = car.get("model")
print(x)

运行结果如下:

911

(4).keys()

返回字典里的所有键

car = {"brand": "Porsche", "model": "911", "year": 1963}
res = car.keys()
print(res)

运行结果如下:

dict_keys(['brand', 'model', 'year'])

(5).values()

返回字典的所有值

car = {"brand": "Porsche", "model": "911", "year": 1963}
res = car.values()
print(res)

运行结果如下:

dict_values(['Porsche', '911', 1963])

(6).items()

返回字典的所有键值对

car = {"brand": "Porsche", "model": "911", "year": 1963}
res = car.items()
print(res)

运行结果如下:

dict_items([('brand', 'Porsche'), ('model', '911'), ('year', 1963)])

(7).del()

删除字典元素

car = {"brand": "Porsche", "model": "911", "year": 1963}
del car["model"]
print(car)

运行结果如下:

{'brand': 'Porsche', 'year': 1963}

(8).zip()

zip()方法将键值打包成一个字典

li1 = ["name","age"]
li2 = ["hacker","18"]
print(dict(zip(li1,li2)))

运行结果如下:

{'name': 'hacker', 'age': '18'}

三、字符串

3.1字符串定义:

字符串就是一系列字符。字符串属于不可变序列,在python中,用引号包裹的都是字符串,其中引号可以是单引号,双引号,也可以是三引号(单,双引号中的字符必须在一行,三引号中的字符可以分布在多行)

txt = 'hello world'  # 使用单引号,字符串内容必须在一行
txt1 = "hello python world "  # 使用双引号,字符串内容必须在一行
# 使用三引号,字符串内容可以分布在多行
txt2 = '''life is short 
i use python '''

3.2字符串常用方法

(1).find()

find()方法返回该元素最小索引值(找不到返回-1)

txt = "hello python world."
res = txt.find("python")
print(res)

运行结果如下:

6

(2).index()

index()方法返回该元素最小索引值(找不到元素会报错)

txt = "hello python world."
res = txt.index("world")
print(res)

运行结果如下:

13

(3).startswith()

startswith() 方法如果字符串以指定值开头,返回True,否则返回False

判断字符串是不是以"hello"开头

txt = "hello python world."
res = txt.startswith("hello")
print(res)

运行结果如下:

True

(4).endswith()

endswith() 方法如果字符串以指定值结束,返回True,否则返回False

判断字符串是不是以"hello"结束

txt = "hello python world."
res = txt.endswith("hello")
print(res)

运行结果如下:

Flase

(5).count()

count() 方法返回指定值在字符串中出现的次数。

txt = "hello python world."
res = txt.count("o")
print(res)

运行结果如下:

3

(6).join()

join() 方法获取可迭代对象中的所有项目,并将它们连接为一个字符串。必须将字符串指定为分隔符

使用"-"作为分割符,将列表中的所有项连接到字符串中

res = ['h','e','l','l','o']
print('-'.join(res))

运行结果如下:

h-e-l-l-o

(7).upper()

upper()方法将字符串全部转为大写

tet = "hello python world"
res = txt.upper()
print(res)

运行结果如下:

HELLO WORLD

(8).lower()

lower()方法将字符串全部转为小写

tet = "HELLO PYTHON WORLD"
res = txt.lower()
print(res)

运行结果如下:

hello python world

(9).split()

split()方法以指定字符分割字符串,并返回列表

以?号作为分隔符,分割字符串

txt = "hello?python?world"
res = txt.split("?")
print(res)

运行结果如下:

['hello', 'python', 'world']

扩展💡分割后打印还是原字符串(字符串是不可变类型,分割操作是复制一份原字符串,更改的是复制出来的那一份)

txt = "hello?python?world"
res = txt.split("?")
# 打印分割后的
print(res)
# 打印原字符串
print(txt)

运行结果如下:

['hello', 'python', 'world']
hello?python?world

(10).strip()

strip()方法删除字符串两端的空格

txt = "    hello  "
res = txt.strip()
print(res)

运行结果如下:

hello

(11).replace()

replace()方法以指定内容替换掉被指定内容(默认替换全部,可指定替换次数)

txt = 'hello python world'
res = txt.replace('python','java')
print(res)

运行结果如下:

hello java world

扩展💡替换后打印还是原字符串(字符串是不可变类型,替换操作是复制一份原字符串,更改的是复制出来的那一份)

txt = 'hello python world'
res = txt.replace('python','java')
# 打印替换后的
print(res)
# 打印原字符串
print(txt)

运行结果如下:

hello java world
hello python world

(12).len()

len()返回字符串长度 # 各容器都能用

a_str = 'hello python world'
print(len(a_str))

运行结果如下:

18

其它:

  • str.upper():将字符串中的所有字母转换为大写形式。
  • str.lower():将字符串中的所有字母转换为小写形式。
  • str.capitalize():将字符串的第一个字母转换为大写,其他字母转换为小写。
  • str.title():将字符串中的每个单词的第一个字母转换为大写。
  • str.strip():删除字符串开头和结尾的空格(或其他指定字符)。
  • str.startswith(prefix):检查字符串是否以指定的前缀开头。
  • str.endswith(suffix):检查字符串是否以指定的后缀结尾。
  • str.split():将字符串分割成子字符串列表,根据默认的分隔符(空格)或指定的分隔符。
  • str.join(iterable):将字符串作为分隔符,将可迭代对象中的元素连接成一个字符串。
  • str.replace(old, new):将字符串中的指定子字符串替换为新的子字符串。
  • str.find(sub):返回子字符串在字符串中第一次出现的索引,如果未找到则返回-1。
  • str.rfind(sub):返回子字符串在字符串中最后一次出现的索引,如果未找到则返回-1。
  • str.index(sub):与find()方法类似,但如果子字符串未找到,则会引发ValueError异常。
  • str.rindex(sub):与rfind()方法类似,但如果子字符串未找到,则会引发ValueError异常。
  • str.count(sub):返回子字符串在字符串中出现的次数。
  • str.isalpha():检查字符串是否只包含字母字符。
  • str.isdigit():检查字符串是否只包含数字字符。
  • str.islower():检查字符串中的所有字母是否都为小写。
  • str.isupper():检查字符串中的所有字母是否都为大写。
  • str.isnumeric():检查字符串是否只包含数值字符。

更多参考:

python基础

posted @ 2022-12-19 13:11  __username  阅读(55)  评论(0编辑  收藏  举报

本文作者:DIVMonster

本文链接:https://www.cnblogs.com/guangzan/p/12886111.html

版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。