1.4 字符串&字典操作

1.4.1 字符串及其索引&切片

字符串的创建

# 单引号
string = 'My name'
# 双引号
string = "My name"
# 三引号,可以跨行
string = '''My


name'''

结果

My name
My name
My


name

注意
1 "任何在这双引号之间的文字”
2 "单引号其实和双引号完全一样”
3 '''三个引号被用于长段文字或说明,只要引号不结束,你就可以任意换行'''
4 字符串属不可变数据类型

关于注释的快捷键
注释前

string = 'My name'
print(string)
string = "My name"
print(string)
string = '''My


name'''
print(string)

注释后(选中代码,按住CTRL+?)

#string = 'My name'
# print(string)
# string = "My name"
# print(string)
# string = '''My
# 
# 
# name'''
# print(string)

索引&切片

合并:'char1'+'char2'+'char3'
重复:'word' * 3
转换:int(string)
切片与索引:
str[0]//取字符串中第一个元素
str[-4]//取字符串中倒数第4个元素
str[1:4]//取字符串中第2个元素到第5个元素(不含)
str[3:]//取字符串中第4个元素及其后边的元素
str[:3]//取字符串中第一个元素直到第4个元素(不含)

1.4.2 字符串常见的操作

字符串的常见方法

在这里插入图片描述

举例

string = 'My name'
res = string*2
print(res)
res = string+' is xxx'
print(res)
res = string.split(sep=',')
print(res)
print(1,string)
res = string.lower()
# string[0] = 'Y'   # 非法操作,字符串属于不可变的数据类型
print(res)

结果

My nameMy name
My name is xxx
['My name']
1 My name
my name

1.4.3 字典的创建及索引

创建

NASDAQ_code = {
    'BIDU':'Baidu',
    'SINA':'Sina',
    'YOKU':'Youku'
}
//NASDAQ_code = {
//    'key':'value',
//    'key':'value'
//}

1、键-值成对出现;
2、键不能重复;
3、键不可更改,值可修改;
4、键来索引值。

出现重复键

dic = {'h':'hello', 
    0.5:[0.3,0.2], 
    'w':'world', 
    'h':0.5
}

结果,舍弃后边那个

{'h': 0.5, 0.5: [0.3, 0.2], 'w': 'world'}

不可以列表做为键

dic1 = {'h':'hello', 0.5:[0.3,0.2], 'w':'world', [0]:0.5}
print(dic1)

结果,错误

Traceback (most recent call last):
  File "C:/Users/18763/PycharmProjects/untitled1/1-2-2.py", line 73, in <module>
    dic1 = {'h':'hello', 0.5:[0.3,0.2], 'w':'world', [0]:0.5}
TypeError: unhashable type: 'list'

访问字典中的元素

res = dic['h']   # 字典中的元素无先后顺序,通过键来访问值

结果

0.5

1.4.4 字典的常用操作

新增键值对

单个

dic['hw'] = 'hello world'  # 新增键值对

结果

{'h': 100, 0.5: [0.3, 0.2], 'w': 'world', 'hw': 'hello world'}

多个

dic.update({1:'2','3':'werty'})   # 新增键值对
print(dic)

结果

{'h': 100, 0.5: [0.3, 0.2], 'w': 'world', 'hw': 'hello world', 1: '2', '3': 'werty'}

删除

del dic['h']
print(dic)

结果

//before:
//{'h': 100, 0.5: [0.3, 0.2], 'w': 'world', 'hw': 'hello world', 1: '2', '3': 'werty'}
//after:
{0.5: [0.3, 0.2], 'w': 'world', 'hw': 'hello world', 1: '2', '3': 'werty'}

1.4.5 字典推导式 _batch

a = {i:i**2 for i in range(10)}
//a = {key:value[ (space)]推导式}
print(a)

结果

{0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64, 9: 81}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值