码迷,mamicode.com
首页 > 编程语言 > 详细

python基础5--字符串

时间:2018-01-28 20:55:30      阅读:153      评论:0      收藏:0      [点我收藏+]

标签:多个   imp   title   大小写   wap   pac   with   strong   border   


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--字符串

标签:多个   imp   title   大小写   wap   pac   with   strong   border   

原文地址:https://www.cnblogs.com/huangqiancun/p/8372197.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!