Python 101: 和字符串相关的经常使用操做

若是你正在找一个轻松愉快,但又紧凑高效的Python视频,Python 101这个系列就是专门为你设计的。咱们会以一个开发者理解编程语言的视角,向你们完整介绍Python语言自己、Python标准库、如何使用Python编写经常使用的代码片断、以及如何管理和发布你的Python代码。现现在,Python已经成为了AI领域最煊赫一时的编程语言,不管你手头的工做是否会用到Python,这绝对都是值得投资的一项编程技能。Don't hesitate, let's go.python

和字符串相关的经常使用操做

泊学4K视频学习
泊学阅读文档git

在Python中,最经常使用的一类数据类型,莫过于字符串了。在接下来的两小节内容里,咱们就来分享和字符串相关的各类最经常使用的操做。编程

如何建立一个字符串

咱们先来看如何建立字符串。和其余弱若类型脚本语言同样,咱们能够用单引号或双引号建立字符串:api

stringInDoubleQuotes = "Hello Python!"
stringInSingleQuotes = 'Hello Python!'

或者,若是字符串的内容须要跨过多行,还可使用“三引号”的形式:数组

stringInTripleQuotes = '''Hello Python!
This might be a long string
going through multiple lines.
'''

基于这样的用法,若是咱们要在字符串中使用双引号,就把它放在单引号包围的字符串里,反之亦然:app

stringInDoubleQuotes = "Hello 'Python'!"
stringInSingleQuotes = 'Hello "Python"!'

而且,咱们还能够在“三引号”包围的字符串里,使用单引号和双引号:ssh

stringInTripleQuotes = '''Hello 'Python'!
This might be a "long string"
acrossing multiple lines.
'''

除了直接用字面值建立字符串以外,咱们还能够用数字类型建立字符串:编程语言

aNumber = 123
aString = str(number)

可是,用字符串建立数字类型的操做,却不必定总能成功。例如,下面的代码,就会致使一个运行时错误:ide

error = int('abc')

'''
Traceback (most recent call last):
  File "/Users/puretears/Desktop/tmp/aa.py", line 2, in <module>
    int('abc')
ValueError: invalid literal for int() with base 10: 'abc'
'''

只有当字符串的字面值真的表示一个数字的时候,转换才能够完成:学习

oneTwoThree = int("123")

另外,字符串在Python中是只读的。一旦建立完成,就不能像C语言同样用位置去修改了。例如,下面的代码,也会致使编译错误:

aString[0] = 0

'''
Traceback (most recent call last):
  File "/Users/puretears/Desktop/tmp/aa.py", line 2, in <module>
    aString[0] = 0
TypeError: 'str' object does not support item assignment
'''

最后一个关于字符串建立要说明的是,在Python 2和Python 3中,默认使用的字符编码是不一样的。Python 2中,使用的是ASCII编码,为了使用unicode编码,须要明确在字符串前面使用小写字母u,像这样:

stringInDoubleQuotes = u"Hello Python!"

虽然,这样的语法在Python 3中也适用,但却不必这样。由于Python 3的字符串,默认使用的就是unicode编码。

经常使用的字符串操做

了解了如何建立字符串以后,咱们来看一些经常使用的字符串操做,它们大多都简单易行。

首先,咱们能够用加号直接链接两个字符串:

action = "Hello "
name = "Mars!"
welcome = action + name # Hello Mars!

其次,咱们能够直接对字符串使用upper()lower()方法转换字符串的大小写:

welcome.upper() # hello mars!
welcome.lower() # HELLO MARS!

第三,咱们能够用stripe()方法直接去掉字符串的首尾空格:

action.strip()

获取API帮助信息

若是咱们要查看字符串类型支持的全部方法,可使用dir方法:

print(dir(action))

'''
['__add__', '__class__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mod__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmod__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'capitalize', 'casefold', 'center', 'count', 'encode', 'endswith', 'expandtabs', 'find', 'format', 'format_map', 'index', 'isalnum', 'isalpha', 'isdecimal', 'isdigit', 'isidentifier', 'islower', 'isnumeric', 'isprintable', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'maketrans', 'partition', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill']
'''

这样,咱们就会获得一个数组,包含了字符串支持的全部操做。若是要查看某个方法的具体帮助,可使用help方法:

print(help(action.count))

'''
count(...) method of builtins.str instance
    S.count(sub[, start[, end]]) -> int

    Return the number of non-overlapping occurrences of substring sub in
    string S[start:end].  Optional arguments start and end are
    interpreted as in slice notation.
'''

这样,咱们就能够看到方法的签名,以及一个简短的描述信息了。

分割字符串

从上面count的描述信息能够看到,它接受一个形如S[start:end]这样的参数,在Python里,这叫作String slicing。当咱们对字符串类型使用[]操做符的时候,既能够像C同样,使用单个字符的位置读取内容:

action[0] # H

也可使用一个range,截取字符串的一部分:

hello = action[0:5] # Hello

要说明的是,在Python里,0:5这样的写法,是一个半闭半开区间,就如同Swift中的0..<5同样。所以,hello的值,是字符串Hello,而不是Hello加上一个空格。

What's next?

以上,就是这一节的内容,咱们了解了字符串的建立、经常使用操做以及获取API帮助的方式。实际上,除了单纯的使用字面值或者数字以外,咱们还可使用某种形式的模板,定制字符串的内容,这叫作string template,在下一节,咱们就来了解它的两种不一样用法。

相关文章
相关标签/搜索