目录

Strings

1. String syntax

2、Strings are sequences

3、String methods


Strings

Python语言真正发挥作用的一个地方是字符串的操作。 本节将介绍Python的一些内置字符串方法和格式化操作。

这种字符串操作模式经常出现在数据科学工作中,并且在这种情况下是Python的一大闪光之处。

1. String syntax

在之前的课程中已经看过了很多字符串的例子,但回顾一下,Python中的字符串可以使用单引号或双引号来定义。 它们在功能上是等价的。

【1】

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

如果您的字符串包含单引号字符(例如表示撇号),则使用双引号会很方便。同样,如果用单引号将其包装起来,很容易创建一个包含双引号的字符串:

【2】

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

如果我们在单引号字符串中包含单引号字母,Python会报错:

【3】

'Pluto's a planet!'File "<ipython-input-3-16d2b0784e8c>", line 1'Pluto's a planet!'^
SyntaxError: invalid syntax

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

[4]

'Pluto\'s a planet!'
"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表示新的一行。

【5】

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

此外,Python的字符串三重引用语法让我们按字面意思包括换行符(即只需在键盘上点击'Enter',而不是使用特殊的'\ n'序列)。 我们已经在文档字符串中看到了这一点,但我们可以在任何想要定义字符串的地方使用它们。

【6】

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

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

【7】

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

2、Strings are sequences

字符串可以看作是有序字母集合,我们可以按照对列表的操作对字符串进行操作:

【8】

# Indexing
planet = 'Pluto'
planet[0]
'P'
# Slicing
planet[-3:]
'uto'

【9】

# How long is this string?
len(planet)
5
# Yes, we can even loop over them
[char+'! ' for char in planet]
['P! ', 'l! ', 'u! ', 't! ', 'o! ']

与列表最大不同的是它们是不可以修改的。

[10]

planet[0] = 'B'
# planet.append doesn't work either
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-12-65a7701f8ef6> in <module>()
----> 1 planet[0] = 'B'2 # planet.append doesn't work eitherTypeError: 'str' object does not support item assignment

3、String methods

像list一样,str也有很多有趣的方法,这里有几个小例子:

[11]

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

[12]

# all lowercase
claim.lower()
'pluto is a planet!'

[13]

# Searching for the first index of a substring
claim.index('plan')
11

[14]

claim.startswith(planet)
True

[15]

claim.endswith('dwarf planet')
False

在字符串和列表之间:.split()和.join()

str.split()将字符串拆成更小的字符串,默认情况下以空格为界;当把字符串拆分成单词列表时很有用。

[16]

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

有时你还想除了空格以外的东西:

[17]

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

str.join()将我们带到另一个方向,将一个字符串列表拼接成一个长字符串,使用它作为分隔符调用的字符串。

[18]

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

[19]

# Yes, we can put unicode characters right in our string literals :)
' 

6.Strings and Dictionaries相关推荐

  1. Udacity机器人软件工程师课程笔记(二十五) - 使用PID控制四轴飞行器 - 四轴飞行器(四旋翼)模拟器

    1.四轴飞行器运动学和动力学模型 在讨论四轴飞行器时,明确定义两个参考坐标系会很有帮助:一个固定的世界坐标系W{W}W和一个牢固地附着到四轴飞行器的质心(CoM)的运动坐标系B{B}B. 假设运动坐标 ...

  2. Coursera课程Python for everyone:chapter9

    Chapter 9 Quiz 10 试题 1. How are Python dictionaries different from Python lists? Python lists mainta ...

  3. 0.Overview

    本文为Kaggle Learn的Python课程的中文翻译,原文链接为:https://www.kaggle.com/learn/python 欢迎来到Kaggle Learn的Python课程.本课 ...

  4. iOS 苹果官方Demo

    GitHub 文章链接地址, 欢迎Star+Fork Mirror of Apple's iOS samples This repository mirrors Apple's iOS samples ...

  5. iOS 苹果官方Demo合集

    转自:https://github.com/WildDylan/appleSample Mirror of Apple's iOS samples This repository mirrors Ap ...

  6. python支持接口编程的好处_面向对象、接口编程的重要性 python 为什么引入接口interface...

    面向对象编程的实践 有个产品,其有10个子产品,现在要统计每日消费数据 其中8个子产品的消费入账金额算法相同,2个不同; 拓展性差的糟糕的代码 def ConsumptionSum(product): ...

  7. Coursera上Python课程(公开课)汇总

    向AI转型的程序员都关注了这个号??? 大数据挖掘DT数据分析  公众号: datadw Python是深度学习时代的语言,Coursera上有很多Python课程,从Python入门到精通,从Pyt ...

  8. python大学课程-Coursera上Python课程(公开课)汇总

    原标题:Coursera上Python课程(公开课)汇总 Python是深度学习时代的语言,Coursera上有很多Python课程,从Python入门到精通,从Python基础语法到应用Python ...

  9. RobotFramework-自定义远程java关键字库能否返回Map类型

    自定义的远程关键字库能使用哪些数据类型来和robotframework交互?先引用官网上的一段话 4.2.3   Supported argument and return value types B ...

最新文章

  1. cve-2017-12629 apache solr xxe rce 漏洞分析
  2. 使用mint-ui开发项目的一些所得
  3. Hadoop的版本介绍
  4. jsoncpp在linux和windows下的编译及使用详解
  5. android颜色选择状态,androidUiAutomator如何根据颜色判断控件的状态
  6. 到底是32位系统运行快还是64位系统快
  7. IDC:2021年全年中国市场折叠屏产品规模约150万台
  8. Monte Carlo采样
  9. python写数据到hive_Python数据篇之Pyhive
  10. TSP-遗传算法求解
  11. WINDOWS CMAKE与NMAKE
  12. git 删除文件后如何恢复此文件
  13. 虚拟化环境高可靠存储的构架和配置
  14. 学习 瑞吉外卖项目——总结
  15. Excel应用技巧:不规则合并单元格之批量填充序列
  16. Android 直播RTMP流
  17. TensorFlow实现语音识别
  18. 三分钟让闲置电脑变云主机
  19. Eclipse的下载、安装与汉化
  20. Excel导出数据 基于注解实现 复制即可用

热门文章

  1. sublime配置python环境变量_Sublime Python环境配置
  2. dataoutputstream.write 有时无法发送_RTK实操——CORS官方网教您如何解决RTK无法固定的问题...
  3. 线程启动语句的顺序是否决定线程的执行次序。_详细分析 Java 中启动线程的正确和错误方式
  4. 阿里云java mysql环境_阿里云搭建centos java mysql nginx环境
  5. UE4 多个static mesh合并成一个static mesh
  6. UE4 多人联机显示每个人的playid
  7. 冠榕智能灯光控制协议分析(controller-node)
  8. ubuntu13.10无法登陆
  9. 五大算法之二--动态规划
  10. 一个数据包大小是多少k_算法交流: 6046 数据包的调度机制 【2.6基本算法之动态规划】...