赞
踩
使用字符串和字典,这两种是Python的基本数据类型。
咱们这篇讲解将涵盖两个重要的Python类型:字符串和字典。
Python语言真正闪耀的一个领域是字符串的操作。
本节将涵盖一些Python内置的字符串方法和格式化操作。在数据科学工作的背景下,这样的字符串操作模式经常出现。
在之前政安晨的Python语言大讲堂的学习中,你已经看到了许多字符串的示例,但为了回顾一下,Python中的字符串可以使用单引号或双引号来定义。它们在功能上是等效的。
- x = 'Pluto is a planet'
- y = "Pluto is a planet"
- x == y
在Miniconda构建的Jupyter Notebook中执行如下:
双引号在字符串中非常方便,如果字符串中包含单引号字符(例如表示撇号)。同样地,如果将字符串用单引号包裹起来,很容易创建包含双引号的字符串。
- print("Pluto's a planet!")
- print('My dog is named "Pluto"')
如果我们尝试将单引号字符放在单引号字符串中,Python会感到困惑:
'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开始新的一行。
比如:
- hello = "hello\nworld"
- print(hello)
此外,Python的字符串三引号语法让我们可以直接包含换行符(即通过键盘上的回车键输入,而不是使用特殊的'\n'序列)。我们已经在函数文档字符串中见过这个用法,但我们可以在任何需要定义字符串的地方使用它们。
- triplequoted_hello = """hello
- world"""
- print(triplequoted_hello)
- triplequoted_hello == hello
print()函数会自动添加换行符,除非我们为关键字参数end指定一个值,该值不等于默认值'\n':
- print("hello")
- print("world")
- print("hello", end='')
- print("pluto", end='')
字符串可以被看作是字符的序列。我们几乎可以对列表做的所有操作,也可以对字符串进行。
- # Indexing
- planet = 'Pluto'
- planet[0]
- # Slicing
- planet[-3:]
- # How long is this string?
- len(planet)
- # Yes, we can even loop over them
- [char+'! ' for char in planet]
但是它们与列表的一个重要区别是它们是不可变的。我们无法修改它们。
像列表一样,字符串类型(str)也有许多非常有用的方法。我在这里只展示一些例子。
- # ALL CAPS
- claim = "Pluto is a planet!"
- claim.upper()
- # all lowercase
- claim.lower()
- # Searching for the first index of a substring
- claim.index('plan')
claim.startswith(planet)
- # false because of missing exclamation mark
- claim.endswith('planet')
我们很重要: .split()
和 .join()
str.split()将一个字符串分割成较小的字符串列表,默认情况下按空格进行分割。这对于从一个大字符串转换成单词列表非常有用。
- words = claim.split()
- words
有时你可能想要以除空格以外的其他字符进行分割:
- datestr = '1956-01-31'
- year, month, day = datestr.split('-')
str.join()把我们带入了另一个方向,将一个字符串列表缝合成一个长字符串,使用调用它的字符串作为分隔符。
'/'.join([month, day, year])
- # Yes, we can put unicode characters right in our string literals :)
- ' 声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/weixin_40725706/article/detail/346544?site推荐阅读
相关标签
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。