python基础5--字符串

栏目: Python · 发布时间: 7年前

内容简介:python基础5--字符串

1 find()、rfind()、index()、rindex()、count()

s = "this apple is red apple"
s.find("apple")
s.find("apple",9)
s.find("apple",1,3) 
s.rfind("app") #从字符串尾部向前查找
s.index("pp")
s.count("p")

2 split()、rsplit()、partition()、rpartition()

partition将字符串分为三部分,分隔符前,分隔符,分隔符后,’r’表示从尾部向前

s.split(' ') #使用空格分割 ['this', 'apple', 'is', 'red', 'apple']
s.partition(' ')  #('this', ' ', 'apple is red apple')

3 join()

多个字符串连接,相邻字符串插入指定字符

s1 = s.split(' ')
sep = "-"
s2 = sep.join(s1) #'this-apple-is-red-apple'

4 lower()、upper()、capitalize()、title()、swapcase()

将字符串转换为小写,大写,首字母大写,每个单词首字母大写,大小写互换

5 replace()

s.replace("apple","orange") #'this orange is red orang'

6 maketrans()、translate()

maketrans()生成字符映射表,translate()按照映射表替换字符,第二个参数为要删除的字符

import string
table = string.maketrans("abcdefg","1234567")
s = "this apple is red apple"
s.translate(table) #'this 1ppl5 is r54 1ppl5'
s.translate(table,"hijk") #删除hijk  'ts 1ppl5 s r54 1ppl5'

7 strip()、rstrip()、lstrip()

删除两端、右端、左端空白字符或指定字符

s = "  abc   "
s.strip() #删除两端空白字符 'abc'
"abdc".strip("a") #删除指定字符
"aabdcaaa".rstrip("a") #删除右端指定字符  'aabdc'

8 eval()

尝试将任意字符转化为表达式进行求值

eval("3+4")
import math
eval('math.sqrt(3)')

9 startswith()、endswith()

判断字符串是否以指定字符串开始或结束

10 isalnum()、isalpha()、isdigit()、isspace()、isupper()、islower()

测试字符串是否为数字或字母,是否为字母,是否为数字,是否为空白,大写,小写


以上所述就是小编给大家介绍的《python基础5--字符串》,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对 码农网 的支持!

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

Pro Git (Second Edition)

Pro Git (Second Edition)

Scott Chacon、Ben Straub / Apress / 2014-11-9 / USD 59.99

Scott Chacon is a cofounder and the CIO of GitHub and is also the maintainer of the Git homepage ( git-scm.com ) . Scott has presented at dozens of conferences around the world on Git, GitHub and the ......一起来看看 《Pro Git (Second Edition)》 这本书的介绍吧!

RGB转16进制工具
RGB转16进制工具

RGB HEX 互转工具

在线进制转换器
在线进制转换器

各进制数互转换器

html转js在线工具
html转js在线工具

html转js在线工具