Python字符串及其他类型

一、Python变量命名规则

“数字字母下划线,数字不能打开头”

 #驼峰命名法
 HelloWorld = 'world'
 #'_'连接
 book_page_num = 123

二、if else判断语句写法

if 7>3:
    print(123)
    if 4<5:
        print(777)
elif 7<3:
    print(456)
else:
    print(789)

三、Python数据类型

Numbers(数字) int float
String(字符串) str
List(列表) list
Tuple(元组)tuple
Dictionary(字典) dict
Set(集合) set
Boolean(布尔) bool
Python 的八个标准数据类型中:

不可变数据类型(5 个):int、float、str、bool、tuple;
可变数据类型(3 个):list、set、dict;

# int
print(23332)
# float
print(1222.222)
# str
str1 = 'hello world'
# list(可变)
print([1,2,3,4])
lists = [1,2,3]
print(id(lists))
lists.append(4)
print(id(lists))
# tuple
print((1,2,3,4))
# set(可变)
print({1,2,3,4})
# dict(可变)
print({'hello':'world',123:'world'})
# bool
# True False

四、字符串的各种操作

1.字符串拼接

可以直接使用“+”号

# 字符串拼接+
str1 = 'hello world'
str2 = 'Hi'
str3 = 'hello world' + 'Hi'
print(str1+str2,str3)

使用id()方法可以查看数据的真实内存地址

print(id(str1))
print(id(str1+str2))
print(id(str3))
hello worldHi hello worldHi
2729388342576
2729389418672
2729389416368

Process finished with exit code 0

2.字符串替换

使用replace()方法,replace(‘要替换的内容’,‘替换后的内容’)

demo1 = '今天天气不错!123456789'
demo2 = demo1.replace('不错','很坏')
print(demo1)
print(demo2)
今天天气不错!123456789
今天天气很坏!123456789

Process finished with exit code 0

3.字符串中字母大小写转换

upper() 全部大写
lower() 全部小写
swapcase() 大小写互转
title() 只有首字母大写(驼峰)

demo1 = 'hello WORLD'
print(demo1.upper())
print(demo1.lower())
print(demo1.swapcase())
print(demo1.title())
HELLO WORLD
hello world
HELLO world
Hello World

Process finished with exit code 0

4.去除字符串左右两遍的 空字符串和指定字符

strip()方法,
lstrip()去除左边
rstrip()去除右边

注: 只能删除最左边和最右边的空白字符和指定字符,
不能删除字符串中间的字符,字符串不可变

# 去左右空白字符及指定字符
demo1 = '    hello    world     123aaaaa'
demo2 = '    hello    world     123aaaaa   '
# 去两边
print(demo1.strip())
# 去左
print(demo1.lstrip())
# 去右
print(demo1.rstrip())
# 去右边s
print(demo1.rstrip('a'))
#当字符串最右边有空白字符时,不能直接清楚指定字符
print(demo2.rstrip('a'))
hello    world     123aaaaa
hello    world     123aaaaa
    hello    world     123aaaaa
    hello    world     123
    hello    world     123aaaaa   

Process finished with exit code 0

5.字符串拆分

split()方法
split(‘_’),指定用’_'拆分,拆分后‘_’不保留
拆分后的每一段存进一个列表

#字符串拆分
demo1 = 'hello world_你好啊_啦啦啦'
list1 = demo1.split('_')
#拆分后的内容以列表存放
print(list1)
['hello world', '你好啊', '啦啦啦']

Process finished with exit code 0

6.列表连成字符串

‘ ’.join()方法 ‘ ’内是指定用来连接的内容

#列表连成字符串
demo1 = 'hello world_你好啊_啦啦啦'
list1 = demo1.split('_')
demo2 = '_'.join(list1)
print(list1)
print(demo2)

['hello world', '你好啊', '啦啦啦']
hello world_你好啊_啦啦啦

Process finished with exit code 0

7.字符串查询

使用字符串下标查询,用

for i in range str1:

遍历字符串中每一个字符
也可以直接像输出列表内容一样,str1[2]取字符串中第3个元素
“计数从0开始,数字+1=要取的元素位置”
倒数第一个是从[-1]开始,[-4]是倒数第四个字符

# 字符串查询
str1 = 'hello world'
for i in str1:
    print(i)
print('******')
print(str1[-4])
h
e
l
l
o
 
w
o
r
l
d
******
o

Process finished with exit code 0


find()方法,查找字符串中指定元素的下标,返回值为数字
index()方法,同样是查找字符串中指定元素的下标,返回值为数字
不同的是:find找不到返回-1 index则是报错

str1 = 'hello world 你好_世界123'
# 字符串查询(取你好三个字)
# find找不到返回-1 index则是报错
# 方法一
a = str1.find('我')
print(a)
b = str1.index('我')
print(b)
Traceback (most recent call last):
  File "D:/PycharmProjects/Python学习/1/demo.py", line 64, in <module>
    b = str1.index('我')
ValueError: substring not found
-1

Process finished with exit code 1

n=14
str1[n+1:n+4] 取字符串中第n+1个到n+4个元素

str1 = 'hello world 你好_世界123'
# 字符串查询(取你好三个字)
# find找不到返回-1 index则是报错
# 方法一
num = str1.find('_')
print(num)
print(str1[num+1:num+4])
# 方法二
num = str1.index('d')
print(str1[num+1:num+4])
14
世界1
 你好

Process finished with exit code 0

8.求字符串长度

len()方法,返回值为int数字

# 求字符串长度
str1 = 'hello world'
print(len(str1))

for i in range(len(str1)):
    print(str1[i])
11
h
e
l
l
o
 
w
o
r
l
d

Process finished with exit code 0

for i in range(2,10,2)的含义:从2开始,遍历到10,每次自增2

for i in range(2,10,2):
    print(i)
2
4
6
8

Process finished with exit code 0

9.字符串倒序

str[ : :-1] 每次自增-1,即为倒序

# 字符串倒序
str1 = 'hello world'
print(str1[::-1])
print(str1[::])
print(str1[::2])
dlrow olleh
hello world
hlowrd

Process finished with exit code 0

10.编码介绍

ASCII码
Unicode
utf8

# ASCII
print(ord('A'))
print(chr(97))
65
a

Process finished with exit code 0

gbk
gb2312
gb18030

encode()是编码
decode()是解码,使用decode解码 可以加一个‘ignore’属性,来忽略需要解码的内容中不能正确解码的内容

“decode的作用是将其他编码的字符串转换成unicode编码,如str1.decode(‘gb2312’),表示将gb2312编码的字符串str1转换成unicode编码。
encode的作用是将unicode编码转换成其他编码的字符串,如str2.encode(‘gb2312’),表示将unicode编码的字符串str2转换成gb2312编码。

总得意思:想要将其他的编码转换成utf-8必须先将其解码成unicode然后重新编码成utf-8,它是以unicode为转换媒介的。”

转载自https://blog.csdn.net/weixin_43670190/article/details/112528900

str1 = '中国'
print(str1.encode('gbk'))
print(str1.encode('gbk').decode('gbk'))
print(str1.encode('utf8'))
str2 = b'\xe4\xb8\xad\xe5\x9b'.decode('utf8','ignore')
print(str2)
b'\xd6\xd0\xb9\xfa'
中国
b'\xe4\xb8\xad\xe5\x9b\xbd'
中

Process finished with exit code 0

11.字符串格式化的三种方式

# strs格式化
# (一)
strs = 'hello world {},{}'.format('法外狂徒','张三')
# (二)
str1 = 'hello world %s'%('张三')
# (三)
zs = '张三'
str2 = f'hello world {zs}'
print(strs)
print(str1)
print(str2)
hello world 法外狂徒,张三
hello world 张三
hello world 张三

Process finished with exit code 0

五、列表

1.增

1)方法1-------追加

list.append()
注:此方法未改变列表真实地址

lists = [1,2,3,4]
# 方法一
lists.append(4)
print(lists)
[1, 2, 3, 4, 4]

Process finished with exit code 0
2)方法2------列表合并(新列表)

直接用 + 号添加
此方法实际上是创建了一个新的列表

lists = [1,2,3,4]
# 方法二
print(lists+[5])
[1, 2, 3, 4, 5]

Process finished with exit code 0

3)方法3------列表合并(原列表)

list.extend()方法
是在原列表上添加数据,未改变列表地址

lists = [1,2,3,4]
# 方法三
lists.extend([6])
print(lists)
[1, 2, 3, 4, 6]

Process finished with exit code 0

4)方法4-------插入

list.insert() 指定列表下标位置插入,未改变列表位置

lists = [1,2,3,4]
# 方法四
lists.insert(2,'4')
lists.insert(3,4)
print(lists)
[1, 2, '4', 4, 3, 4]

Process finished with exit code 0

2.删

1)方法一 -------pop弹出

list.pop() 方法
可指定列表下表,弹出元素,默认弹出列表最后一个元素,可被变量接

# 删除
lists = [1,2,3,4]
# 方法一
num = lists.pop(0)
num1 = lists.pop()
print(num)
print(num1)
print(lists)
1
4
[2, 3]

Process finished with exit code 0
2)方法二 remove移除

list.remove()
list.remove(‘要移除的元素’) 直接移除指定元素
list.remove(list[N]) 移除列表的第N+1个元素

lists = [1,2,3,4,5,6]
# 方法二
lists.remove(lists[4])
print(lists)
lists.remove(3)
print(lists)
[1, 2, 3, 4, 6]
[1, 2, 4, 6]

Process finished with exit code 0
3)方法三-------clear清空

list.clear()
直接清空列表

lists = [1,2,3,4,5,6]
# 方法三
lists.clear()
print(lists)
[]

Process finished with exit code 0

3.改

直接指定列表元素下标修改

lists = [1,2,3,4]
# 修改
lists[2] = 'hello'
print(lists)
[1, 2, 'hello', 4]

Process finished with exit code 0
------------------------坑---------------------------
# 坑
lists = [1,2,3,4]
lists[1:3] = 'qqq'
print(lists)
print(lists[5:111])
[1, 'q', 'q', 'q', 4]
[]

Process finished with exit code 0

4.查

1)方法1-------for遍历列表

for i in lists:
遍历整个数组

# 方法一
lists = [1,2,3,4]
for i in lists:
    print(i)
1
2
3
4

Process finished with exit code 0
2)方法2-------for遍历列表下标

用len()方法取列表长度,用下标遍历数组

# 方法二
lists = [1,2,3,4]
for i in range(len(lists)):
    print(lists[i])
1
2
3
4

Process finished with exit code 0
3)遍历二重列表

使用嵌套for循环遍历

# 遍历多个值的列表
lists = [[1,2],[3,4],[5,6]]
for i in lists:
    for j in i:
        print(j)
1
2
3
4
5
6

Process finished with exit code 0

对应列表值遍历,不需要的元素用‘_’代替

lists = [[1,2,3],[4,5,6],[6,7,8]]
for a,b,_ in lists:
    print(a,b)
for a,_,b in lists:
    print(a,b)
1 2
4 5
6 7
1 3
4 6
6 8

Process finished with exit code 0

5.列表生成式

1)生成偶数数列和奇数数列

%是取余
// 是取整

# 要奇数
lists = [x for x in range(1,101) if x%2==1]
print(lists)
# # 要偶数
lists1 = [x for x in range(1,101) if x%2==0]
print(lists1)
# 偶数为正奇数为负
lists2 = [-x if x%2==1 else x for x in range(1,101)]
print(lists2)

[1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23, 25, 27, 29, 31, 33, 35, 37, 39, 41, 43, 45, 47, 49, 51, 53, 55, 57, 59, 61, 63, 65, 67, 69, 71, 73, 75, 77, 79, 81, 83, 85, 87, 89, 91, 93, 95, 97, 99]
[2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30, 32, 34, 36, 38, 40, 42, 44, 46, 48, 50, 52, 54, 56, 58, 60, 62, 64, 66, 68, 70, 72, 74, 76, 78, 80, 82, 84, 86, 88, 90, 92, 94, 96, 98, 100]
[-1, 2, -3, 4, -5, 6, -7, 8, -9, 10, -11, 12, -13, 14, -15, 16, -17, 18, -19, 20, -21, 22, -23, 24, -25, 26, -27, 28, -29, 30, -31, 32, -33, 34, -35, 36, -37, 38, -39, 40, -41, 42, -43, 44, -45, 46, -47, 48, -49, 50, -51, 52, -53, 54, -55, 56, -57, 58, -59, 60, -61, 62, -63, 64, -65, 66, -67, 68, -69, 70, -71, 72, -73, 74, -75, 76, -77, 78, -79, 80, -81, 82, -83, 84, -85, 86, -87, 88, -89, 90, -91, 92, -93, 94, -95, 96, -97, 98, -99, 100]

Process finished with exit code 0
2)一行代码取出二维列表的值

从[[1,2,3],[4,5,6]] 取出[1,2,3,4,5,6]

# 一行代码打开如下列表([1,2,3,4,5,6])
lists = [[1,2,3],[4,5,6]]
list1 = [ y for x in lists for y in x]
print(list1)
[1, 2, 3, 4, 5, 6]

Process finished with exit code 0
3)查看某元素在列表中的个数 count()

list.count()

# 查看某元素在列表中的个数
lists = [1,2,3,4,2]
print(lists.count(2))
2

Process finished with exit code 0
4)判断某值是否在列表中—if

直接用if 语句判断

lists = [1,2,3,4,5]
if 4 in lists:
    print('yes')
else:
    print('no')
if 6 in lists:
    print('yes')
else:
    print('no')
yes
no

Process finished with exit code 0

6.多变量赋值

两种方法相同

# 多变量赋值
a,b,c = [2,3,4]
print(a,b,c)
a,b,c = 2,3,4
print(a,b,c)
2 3 4
2 3 4

Process finished with exit code 0

7.斐波那契数列

# 斐波那契数列
lists = [1,1,2,3,5,8,13]
x = 1
y = 1
list1 = []
for n in range(20):
    list1.append(x)
    x,y = y,x+y
print(list1)
[1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597, 2584, 4181, 6765]

Process finished with exit code 0

8.实现strip()函数的功能

1)方法一
strs = '        abcd  ess      '
print(len(strs))
for n in range(len(strs)):
    if strs[0]==' ':
        strs = strs[1:]
    elif strs[-1] == ' ':
        strs = strs[:-1]
    else:
        break
print(strs)

23
abcd  ess

Process finished with exit code 0
2)方法二
# 方法二
strs = '        abcd  ess      '
for n in range(len(strs)):
    m = 0
    if strs[0]==' ':
        strs = strs[1:]
    else:
        m+=1
    if strs[-1] == ' ':
        strs = strs[:-1]
    else:
        m+=1

    if m==2:
        break
print(strs)

abcd  ess

Process finished with exit code 0

六、字典

字典的特性:
无序无下标
字典的键不能重复,键不能是可变元素
相同的键,后面的键值会覆盖前面的键值

print(type({})) #字典
#{}是列表

<class 'dict'>

Process finished with exit code 0

1.增

1)方法一-------update更新

使用dict.update({‘键’:‘值’})

dicts = {'hello':'world',123:'world',(1,2,3):444}
# 增
# 方法一
dicts.update({'nihao':'dadigua'})
print(dicts)
{'hello': 'world', 123: 'world', (1, 2, 3): 444, 'nihao': 'dadigua'}

Process finished with exit code 0
2)方法二

直接新增键值对

dicts = {'hello':'world',123:'world',(1,2,3):444}
# 方法二
dicts['nihao'] = 'dadigua'
print(dicts)
{'hello': 'world', 123: 'world', (1, 2, 3): 444, 'nihao': 'dadigua'}

Process finished with exit code 0

2.删

1)方法一 ----------pop弹出

dict.pop(键)

# 删除
# 方法一
dicts = {'hello':'world',123:'world',(1,2,3):444}
v = dicts.pop('hello')
print(v,dicts)
world {123: 'world', (1, 2, 3): 444}

Process finished with exit code 0

2)方法二-----------del删除

del dicts[键] ----------- 注:[ ] 方括号

# 方法二
dicts = {'hello':'world',123:'world',(1,2,3):444}
del dicts['hello']
print(dicts)

{123: 'world', (1, 2, 3): 444}

Process finished with exit code 0

3.改

1)方法一------直接修改
{'hello': 1234, 123: 'world', (1, 2, 3): 444}

Process finished with exit code 0

{'hello': 1234, 123: 'world', (1, 2, 3): 444}

Process finished with exit code 0

4.查

1)查询所有的键
print(dicts.keys())
2)查询所有的值
print(dicts.values())
3)遍历方法一
 for i in dicts:
     print(i,dicts[i])
4)遍历方法二-----------items()

dicts.items()方法

# 遍历方法二
dicts = {'hello':'world',123:'world',(1,2,3):444}
print(dicts.items())
for a,b in dicts.items():
    print(a,b)

dict_items([('hello', 'world'), (123, 'world'), ((1, 2, 3), 444)])
hello world
123 world
(1, 2, 3) 444

Process finished with exit code 0

七、布尔

1.True和False

非0数字都是True
空字典,空字符串,None,0,False都是 False

# bool
# True False
if '':
    print(123)

if 0:
    print(456)

if False:
    print(789)

if None:
    print(111)

if {}:
    print(222)

if 1:
    print(333)

333

Process finished with exit code 0

八、集合

集合无序,可变,自带去重功能

sets{ }是字典
新建集合用 sets( )
空集合 sets( [ ] )

#空集合
print(set([]))

a=set(['ti','wu',3,4,5])
sets = {'你','好','啊'}
print(a)
print(sets)

set()
{3, 4, 5, 'ti', 'wu'}
{'啊', '你', '好'}

Process finished with exit code 0

1、增

sets.add()方法

sets = {1,2,3,4,5}
# 增
sets.add('A')
print(sets)
{1, 2, 3, 4, 5, 'A'}

Process finished with exit code 0

2、查

集合不能根据下标查询(直接报错),只能遍历

sets = {1,2,3,4,5,'A'}
# 查
# print(sets[0])
for i in sets:
    print(i)
1
2
3
4
5
A

Process finished with exit code 0

3、删

1)方法一-------pop

sets.pop() 默认弹出最左边第一个

sets = {1,2,3,4,5,'A'}
# 删
sets.pop()
print(sets)

{2, 3, 4, 5, 'A'}

Process finished with exit code 0
2)方法二-------remove

sets.remove(要删除的元素)
remove不存在的元素会报错

sets = {1,2,3,4,5,'A'}
sets.remove(3)
print(sets)
{1, 2, 4, 5, 'A'}

Process finished with exit code 0

九、元组

元组能遍历,能根据下标取值,但不能修改

# 元组
tuples = (1, 2, 3,'A','B')
print(tuples[0],tuples[4])
1 B

Process finished with exit code 0

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值