python之关于字符串、字典的那些事

python关于字符串(strings)、字典(dictionaries)的那些事👂

Reference: Kaggle Notebook! Strings and Dictionaries! Click me!

1. 字符串(strings)

本小节将介绍一些python中关于内置字符串的方法和格式,这种字符串操作模式经常会在数据分析工作中碰到,非常实用哦!跟着我一起学习吧;

A. 语法

下面是关于字符串语法的总结!纯干货!!

1、字符串可以使用单引号或者双引号;
2、但如果字符串内本来就带有单引号(don’t),那就得用双引号了,不然python会无法识别哦;
3、同样,如果字符串内本来带有双引号,那定义字符串的时候就得使用单引号啦
4、不过上述问题都可以用反斜杠来解决;也就是字符串内的单引号或者双引号前面可带反斜杠( \ ),即可避免无法python无法识别的情况;

请看例子:

>>> x = 'apple'
>>> y = "apple"
>>> x == y
True
>>> print("I don't like it")
I don't like it
>>> print('My dog is named "Rose"')
My dog is named "Rose"
>>> print('I don\'t like it') # 反斜杠\'
I don't like it
符号输出例子结果
\ ’'What \ ‘s up?’What’s up?
\ """That’s \ "cool \ " "That’s “cool”
\ \\"Look, a mountain: /\ \ "Look, a mountain: /\
\n“1 \n2 3”1 (换行)2 3

换行:

>>> print("hello \nworld")
hello 
world

除了单引号、双引号,还有三引号!
三引号的用法:输入是怎么样,输出就是怎么用;也就是输入的时候有换行,输出就会换行;

>>> print("""hello 
world""")
hello
world
>>> print("""hello world""")
hello world

输出都在同一行:

>>> print('hello', end = ' ')
>>> print('world', end = ' ')
helloworld

B.字符串是有序列的

可以把字符串看作是一串字符序列;

>>> planet = 'Pluto'
>>> planet[0]
'P'
>>> planet[-3:]
'uto'
>>> len(planet)
5
>>> [char + '!' for char in planet]
['P!', 'l!', 'u!', 't!', 'o!']

以上关于数列的知识点在之前的Blog中就写过哦,如有需要请移步:关于数列的那些事

但是!字符串和真正数列的不同之处在于字符串不可被修改!

>>> planet[0] = 'B'
TypeError #会报错

C. 内置字符串的方法

跟数列一样,字符串也有很多可调用的方法;

请看下面例子吧:

字符串转换为大写字母:

>>> claim = "Pluto is a planet!"
>>> claim.upper() 
'PLUTO IS A PLANET!'

字符串转换为小写字母:

>>> claim.lower()
'pluto is a planet'

查找序列号:

>>> claim.index('plan')
11 # 空格也算是一个字符,‘plan’的‘p'是第11位,首位记得是为0哦

检查字符串开头是否某元素,返回True或者False:

>>> claim.startswith('Pluto')
True
>>> claim.startswith('planet')
False

检查字符串是否以某元素结尾,返回True 或者False:


>>> claim.endswith('planet')
False
>>> claim.endswith('!')
True

除了以上几种方法,还有 .split().join()

str.split() 是指将字符串拆分为一组更小的字符串,默认情况下会在空白处断开。也就是将一长串字符串拆分为一个单词列表:

>>> claim.split()
['Pluto', 'is', 'a', 'planet!']

但是,如果你不喜欢在空白处断开,你也可以自定义:

>>> datestr = '1956-01-31'
>>> year, month, day = datestr.split('-')
>>> year
'1956'
>>> month
'01'
>>> day
'31'

str.join() 是指将一串字符串合并成一个长字符串,还可以指定分隔符:

>>> '/'.join([month,day,year])
'01/31/1956'

用format() 构建字符串:

>>> planet = 'Pluto'
>>> planet + ', we miss you.'
'Pluto, we miss you.'

但是如果要加入一些非字符串的数据类型时,要先将该数据类型转为str,才能使用 “+”。

>>> position = 9
>>> planet + ", you'll always be the " + str(position) + "th planet to me."
"Pluto, you'll always be the 9th planet to me."

上述的写法看起来很难阅读以及很烦,因此有了format()这玩意:

"{}, you'll always be the {}th planet to me.".format(planet, position)
"Pluto, you'll always be the 9th planet to me."

解析:
str.format()是一个非常方便的函数,会将所有数据类型都自动转换为str,如上述例子,将 “position” 自动转换为str;然后就会将format右侧的变量填入format左侧大括号{ } 中;

再看一个关于format()的例子吧

pluto_mass = 1.303 * 10**22
earth_mass = 5.9722 * 10**24
population = 52910390
# 第二个{:.2}代表只留2个小数点,第三个{:.3%}代表留3个小数点并加%,第四个{:,}代表使用千位分隔符,即每隔三位数加一个逗号
"{} weighs about {:.2} kilograms ({:.3%} of Earth's mass). It is home to {:,} Plutonians.".format(
    planet, pluto_mass, pluto_mass / earth_mass, population,
)

输出:

"Pluto weighs about 1.3e+22 kilograms (0.218% of Earth's mass). It is home to 52,910,390 Plutonians."

还可以按索引引用参数:

# 从0开始,按索引引用参数
s = """Pluto's a {0}.
No, it's a {1}.
{0}!
{1}!""".format('planet', 'dwarf planet')
print(s)

输出:

Pluto's a planet.
No, it's a dwarf planet.
planet!
dwarf planet!

2. 字典(Dictionaries)

字典是指内置的python数据结构,每个关键字都有对应的值;

看个例子就懂了~

numbers = {‘one’:1, ‘two’:2, ‘three’:3} #建立一个字典

在这个例子里,‘one’、‘two’、‘three’就是关键字(key),而1,2,3就是所对应的值。

字典建立完成后,即可通过方括号进行访问,具体写法类似列表的索引:

>>> numbers['one']
1

还可以使用这个语法来加其他关键字和其值:

>>> numbers['eleven'] = 11
>>> numbers
{'one': 1, 'two': 2, 'three': 3, 'eleven': 11}

还可以改值:

>>> numbers['one'] = 'Pluto'
>>> numbers
{'one': 'Pluto', 'two': 2, 'three': 3, 'eleven': 11}

Dictionary comprehensions:

planets = ['Mercury', 'Venus', 'Earth', 'Mars', 'Jupiter', 'Saturn', 'Uranus', 'Neptune']
planet_to_initial = {planet: planet[0] for planet in planets} # 创建新字典,key为原来列表的元素,value为对应元素的首字母
planet_to_initial

输出:

{'Mercury': 'M',
 'Venus': 'V',
 'Earth': 'E',
 'Mars': 'M',
 'Jupiter': 'J',
 'Saturn': 'S',
 'Uranus': 'U',
 'Neptune': 'N'}

in运算:

>>> 'Saturn' in planet_to_initial
True
>>> 'apple' in planet_to_initial
False

for循环:

numbers = {'one':1, 'two':2, 'three':3}
for k in numbers:
    print("{} = {}".format(k, numbers[k])) # k是指key,将key填在第一个大括号中,numbers[k]是指每个key所对应的value,并填在第二个大括号里

输出:

one = 1
two = 2
three = 3

我们还可以用 dict.keys() 和 dict.values()将key和value提取出来:

>>> ' '.join(sorted(planet_to_initial.values())) # 将planet_to_initial的value提取出来,并用sorted将字母排序
'E J M M N S U V'

dict.items() 允许我们同时迭代字典里的key和value:

for planet, initial in planet_to_initial.items():
    print("{} begins with \"{}\"".format(planet.rjust(10), initial))

输出:

   Mercury begins with "M"
     Venus begins with "V"
     Earth begins with "E"
      Mars begins with "M"
   Jupiter begins with "J"
    Saturn begins with "S"
    Uranus begins with "U"
   Neptune begins with "N"

解析:
str.rjust() 返回字符串右对齐,必须带一个参数width;

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值