Python3简明教程(七)—— 字符串

字符串是 Python 中最常用的数据类型。本节实验将会学习如何对 Python3 的字符串进行处理操作。

字符串的三种表示

可以通过几种不同的方式表示字符串。如单引号('...')或双引号("...")。下面的例子能帮助你更好的理解字符串。

>>> s = "I am Chinese"
>>> s
'I am Chinese'
>>> s = 'I am Chinese'
>>> s = "Here is a line \
... split in two lines"
>>> s
'Here is a line split in two lines'
>>> s = "Here is a line \n split in two lines"
>>> s
'Here is a line \n split in two lines'
>>> print(s)
Here is a line
 split in two lines

\ 表示写到下一行。如果你想要分几行输入字符串,并且希望行尾的换行符自动包含到字符串当中,可以使用三对引号:"""...""" 或 '''...''' 。

>>> print("""\
... Usage: thingy [OPTIONS]
...      -h                        Display this usage message
...      -H hostname               Hostname to connect to
... """)
Usage: thingy [OPTIONS]
     -h                        Display this usage message
     -H hostname               Hostname to connect to

 

字符串的方法

每一个字符串对象都有几个可用的内建方法,我们已经使用过一些了,比如 s.split()

方法 title() 返回字符串的标题版本,即单词首字母大写其余字母小写。

>>> s = "shi yan lou"
>>> s.title()
'Shi Yan Lou'

方法 upper() 返回字符串全部大写的版本,反之 lower() 返回字符串的全部小写版本。

>>> z = s.upper()
>>> z
'SHI YAN LOU'
>>> z.lower()
'shi yan lou'

方法 swapcase() 返回字符串大小写交换后的版本 。

>>> s = "I am A pRoGraMMer"
>> s.swapcase()
'i AM a PrOgRAmmER'

方法 isalnum() 检查所有字符是否只有字母和数字,下面的代码中第一行的字符串 s 中包含空格字符,所以返回 False

>>> s = "jdwb 2323bjb"
>>> s.isalnum()
False
>>> s = "jdwb2323bjb"
>>> s.isalnum()
True

方法 isalpha() 检查字符串之中是否只有字母。

>>> s = "SankarshanSir"
>>> s.isalpha()
True
>>> s = "Sankarshan Sir"
>>> s.isalpha()
False

还有一些其它检查字符串的方法:

>>> s = "1234"
>>> s.isdigit() # 检查字符串是否所有字符为数字
True
>>> s = "ShiYanLou is coming"
>>> s.islower() # 检查字符串是否所有字符为小写
False
>>> s = "Shiyanlou Is Coming"
>>> s.istitle() # To 检查字符串是否为标题样式
True
>>> s = "CHINA"
>>> s.isupper() # 检查字符串是否所有字符为大写
True

字符串的分割与连接

我们可以使用 split() 分割任意字符串,split() 允许有一个参数,用来指定字符串以什么字符分隔(默认为 " "),它返回一个包含所有分割后的字符串的列表。

>>> s = "We all love Python"
>>> s.split()
['We', 'all', 'love', 'Python']
>>> x = "shiyanlou:is:waiting"
>>> x.split(':')
['shiyanlou', 'is', 'waiting']

相反的,方法 join() 使用指定字符连接多个字符串,它需要一个包含字符串元素的列表作为输入然后连接列表内的字符串元素。

>>> "-".join("GNU/Linux is great".split())
'GNU/Linux-is-great'

在上面的例子中,我们基于空格 " " 分割字符串 "GNU/Linux is great",然后用 "-" 连接它们。

字符串的剥离

字符串有几个进行剥离操作的方法。最简单的一个是 strip(chars),用来剥离字符串首尾中指定的字符,它允许有一个字符串参数,这个参数为剥离哪些字符提供依据。不指定参数则默认剥离掉首尾的空格和换行符,代码如下:

>>> s = "  a bc\n "
>>> s.strip()
'a bc'

你可以使用 lstrip(chars) 或 rstrip(chars) 只对字符串左或右剥离。

>>> s = "www.foss.in" 
>>> s.lstrip("cwsd.") #删除在字符串左边出现的'c','w','s','d','.'字符
'foss.in'
>>> s.rstrip("cnwdi.") #删除在字符串右边出现的'c','n','w','d','i','.'字符
'www.foss'

文本搜索

字符串有一些方法能够帮助你搜索字符串里的文本或子字符串。下面给出示例:

>>> s = "faulty for a reason"
>>> s.find("for")
7
>>> s.find("fora")
-1
>>> s.startswith("fa") # 检查字符串是否以 fa 开头
True
>>> s.endswith("reason") # 检查字符串是否以 reason 结尾
True

find() 能帮助你找到第一个匹配的子字符串,没有找到则返回 -1。

 

两个实例

回文检查

回文(palindrome)是一种无论从左还是从右读都一样的字符序列。比如 “madam”。在这个例子中,我们检查用户输入的字符串是否是回文,并输出结果。

#!/usr/bin/env python3
s = input("Please enter a string: ")
z = s[::-1]  #把输入的字符串s 进行倒序处理形成新的字符串z
if s == z:
    print("The string is a palindrome")
else:
    print("The string is not a palindrome")

单词计数

在讲解单词计数之前我们先了解一个概念:格式化操作符(%)。

我们先看下面的这个例子:

>>> print("my name is %s. I am %d years old" % ('Shixiaolou',4))
my name is Shixiaolou. I am 4 years old

在这个例子中,%s 为第一个格式符,表示一个字符串;%d 为第二个格式符,表示一个整数。格式符为真实值预留位置,并控制显示的格式。常用的有:

%s 字符串(用 str() 函数进行字符串转换)

%r 字符串(用 repr() 函数进行字符串转换)

%d 十进制整数

%f 浮点数

%% 字符“%”

那么接下来我们对用户输入的一行文本进行单词计数。

#!/usr/bin/env python3
s = input("Enter a line: ")
print("The number of words in the line are %d" % (len(s.split(" "))))

 

 

参考链接:https://www.shiyanlou.com/courses/596

posted @ 2019-02-14 12:23  Rogn  阅读(428)  评论(0编辑  收藏  举报