6、Python字符串和字典

本文介绍了Python中的字符串和字典。字符串是不可变的字符序列,提供了多种内置方法,如切片、查找、替换等。可以使用 `split()` 和 `join()` 在字符串和列表之间转换。格式化字符串使用`f-string`简洁且强大。字典是键值对的数据结构,通过键进行访问、添加和修改值。字典理解与循环提供了便捷的操作方式。
摘要由CSDN通过智能技术生成

使用字符串和字典这两种基本的 Python 数据类型

本课将介绍两种基本的 Python 类型: 字符串字典

1.字符串

Python 语言真正出色的一个地方就是在字符串的处理上。本节将介绍一些 Python 内置的字符串方法和格式化操作。

在数据科学工作的背景下,这样的字符串处理模式经常出现。

字符串语法

在前面的课程示例中,你已经看到了很多字符串,但为了复习一下,Python 中的字符串可以使用单引号或双引号来定义,它们在功能上是等效的。

In [1]:

x = 'Pluto is a planet'
y = "Pluto is a planet"
x == y

Out[1]:

True

如果您的字符串包含一个引号字符(例如,表示一个撇号) ,那么双引号非常方便。

类似地,如果用单引号括起来,就很容易创建一个包含双引号的字符串:

In [2]:

print("Pluto's a planet!")
print('My dog is named "Pluto"')
Pluto's a planet!
My dog is named "Pluto"

如果我们尝试将单引号字符放入单引号字符串中,Python 会感到困惑:

In [3]:

'Pluto's a planet!'
  File "/tmp/ipykernel_19/1561186517.py", line 1
    'Pluto's a planet!'
           ^
SyntaxError: invalid syntax

我们可以通过使用反斜杠“转义”单引号来解决这个问题。

In [4]:

'Pluto\'s a planet!'

Out[4]:

"Pluto's a planet!"

下表总结了反斜杠字符的一些重要用法。

What you type… What you get example print(example)
\' ' '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

最后一个序列\n 表示换行符,它使 Python 开始一个新行。

In [5]:

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

此外,Python 的三引号字符串语法允许我们直接包含换行(即通过在键盘上按 ‘Enter’ 键,而不是使用特殊的 ‘\n’ 序列)。我们已经在用于记录函数的文档字符串中见过这个用法,但我们可以在任何需要定义字符串的地方使用它们。

In [6]:

triplequoted_hello = """hello
world"""
print(triplequoted_hello)
triplequoted_hello == hello
hello
world

Out[6]:

True

print() 函数会自动添加换行符,除非我们为关键字参数 end 指定一个值,而不使用默认值 '\n'

In [7]:

print("hello")
print("world")
print("hello", end='')
print("pluto", end='')
hello
world
hellopluto

字符串是序列

字符串可以看作是字符序列。几乎所有我们看到的,我们可以对列表做的事情,我们也可以对字符串做。

In [8]:

# Indexing
planet = 'Pluto'
planet[0]

Out[8]:

'P'

In [9]:

# Slicing
planet[-3:]

Out[9]:

'uto'

In [10]:

# How long is this string?
len(planet)

Out[10]:

5

In [11]:

# Yes, we can even loop over them
[char+'! ' for char in planet]

Out[11]:

['P! ', 'l! ', 'u! ', 't! ', 'o! ']

但是它们与列表的主要区别在于它们是不可变的,我们不能修改它们。

In [12]:

planet[0] = 'B'
# planet.append doesn't work either
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
/tmp/ipykernel_19/2683731249.py in <module>
----> 1 planet[0] = 'B'
      2 # planet.append doesn't work either

TypeError: 'str' object does not support item assignment

字符串方法

list 类似,str 类型有很多非常有用的方法。

In [13]:

# 大写字母
claim = "Pluto is a planet!"
claim.upper()

Out[13]:

'PLUTO IS A PLANET!'

In [14]:

# 都是小写
claim.lower()

Out[14]:

'pluto is a planet!'

In [15]:

# 搜索子字符串的第一个索引
claim.index('plan')

Out[15]:

11

In [16]:

claim.startswith(planet)

Out[16]:

True

In [17]:

# 
  • 22
    点赞
  • 18
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

AI算法蒋同学

你的鼓励将是我创作的最大动力!

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值