首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

计算机二级Python考点解析5

当下 ║ 2018.08.14

人生苦短,我们都要用Python,大家要经常回看大纲~

考试内容二、Python语言基本数据类型

第四部分:字符串类型的操作:字符串操作符、处理函数和处理方法。

字符串操作符

常用的字符串操作符有

x+y:连接两个字符串x和y

x*n:复制n次字符串x

下表实例变量a值为字符串 "Hello",b变量值为 "Python":

字符串处理函数和处理方法

len(x):字符串的长度;

str(x):任意类型x转为字符串形式;

hex(x):整数x转为十六进制小写形式字符串;

oct(x):整数x转为八进制小写形式字符串;

chr(x):x为unicode编码,返回对应的字符;

ord(x):x为字符,返回对应的Unicode编码;

str.*形式的函数

str.lower()或者str.upper():返回字符串的副本,全部字符小写或者大写;

str.count(sub):返回子串sub在str中出现的次数;

str.center(width[,fillchar]):字符串str根据宽度width居中,fillchar可选,默认为空格;

>>> s='abdDEFG'

>>> s.lower()

'abddefg'

>>> s.upper()

'ABDDEFG'

>>> s.count('d')

1

>>> s.center(20)

' abdDEFG '

>>> s.center(20,'*')

'******abdDEFG*******

find 方法

作用:在一个较长字符串中查找子串。返回子串所在位置的最左端索引,如果没有找到则返回-1.如果指定 beg(开始) 和 end(结束) 范围,则检查是否包含在指定范围内,如果包含子字符串返回开始的索引值,否则返回-1。

用法:string.find()

>>> a = 'i am a boy with no money'

>>> print a.find('a')

2

>>> print a.find('a',10,len(a))

-1 #在字符串a的第10到最后一位无法找到字符a,则返回-1

>>> sep = '+'

>>> print sep.join(seq)

1+2+3+4+5

>>> dirs = '','usr','bin','env'

>>> print '/'.join(dirs)

/usr/bin/env

>>> print os.path.join('/hello/','good/boy/','doiido')

/hello/good/boy/doiido

replace 方法

作用:Python replace()方法把字符串中的old(旧字符串)替换成 new(新字符串),如果指定第三个参数max,则替换不超过 max 次。

语法:str.replace(old, new[, max])

参数:

old – 将被替换的子字符串。

new – 新字符串,用于替换old子字符串。

max – 可选字符串, 替换不超过 max 次

>>> str = "this is string example....wow!!! this is really string"

>>> print str.replace("is", "was")

thwas was string example....wow!!! thwas was really string

>>> print str.replace("is", "was", 3)

thwas was string example....wow!!! thwas is really string

split方法

Python split()通过指定分隔符对字符串进行切片,如果参数num有指定值,则仅分隔 num 个子字符串

split()方法语法:

str.split(str=”“, num=string.count(str)).

参数

str –分隔符,默认为所有的空字符,包括空格、换行(\n)、制表符(\t)等。

num –分割次数。

返回分割后的字符串列表。

>>> str = "Line1-abcdef \nLine2-abc \nLine4-abcd"

>>> print str.split( )

['Line1-abcdef', 'Line2-abc', 'Line4-abcd']

>>> print str.split(' ', 1 )

['Line1-abcdef', '\nLine2-abc \nLine4-abcd']

该来的终究会来,没有任何例外和奇迹。

E

N

D

  • 发表于:
  • 原文链接https://kuaibao.qq.com/s/20180814G1UJ4X00?refer=cp_1026
  • 腾讯「腾讯云开发者社区」是腾讯内容开放平台帐号(企鹅号)传播渠道之一,根据《腾讯内容开放平台服务协议》转载发布内容。
  • 如有侵权,请联系 cloudcommunity@tencent.com 删除。

扫码

添加站长 进交流群

领取专属 10元无门槛券

私享最新 技术干货

扫码加入开发者社群
领券