您的位置:首页 > 编程语言 > Python开发

Python学习笔记4_字符串

2015-07-15 16:25 615 查看

字符串操作

字符串基本操作

字符串是序列的一种,所以序列通用的操作,字符串都可以,诸如索引,分片,乘法,自各成员等,需要注意的是字符串属于不可变序列。

字符串格式化

#使用%进行字符串格式化,最基本用法
name = 'Leon'
sentence = 'My name is %s'
print(sentence % name)


运行结果:

My name is Leon


#使用元组或字典格式化一个以上的值
formatVals = 'Leon',23
sentence2 = 'My name is %s,I\'m %i years old'
print(sentence2 % formatVals)
print("%s is a %s" % ('Lily','girl'))


运行结果:

My name is Leon,I'm 23 years old
Lily is a girl


#使用模版进行字符串格式化[类似于UNIX SHELL里的变量替换]
from string import Template
t2 = Template('Hi,$name1!I\'m $name2')
str2 = t2.substitute(name1='Lucy',name2='Leon')
print(str2)


运行结果:

Hi,Lucy!I'm Leon


##格式化单词的一部分
t3 = Template('Hello,${x}ld!')
str3 = t3.substitute(x='wor')
print(str3)


运行结果:

Hello,world!


#使用字典格式进行格式化[safe_substitute为substitute的安全方式]
t4 = Template('$name is $doing!')
dic4 = {}
dic4['name'] = 'Lily'
dic4['doing'] = 'running'
str4 = t4.substitute(dic4)
print(str4)


运行结果:

Lily is running!


更复杂完整的字符串格式化诸如字段宽度,对齐等。转换说明:



转换类型:



print("PI=%f" % 3.1415)
print("PI=%.3f" % 3.1415)
print("PI=%10.3f" % 3.1415)
print("PI=%-10.3f" % 3.1415)
print("PI=%010.3f" % 3.1415)
print("PI=%+-10.3f" % 3.1415)
print("PI=%+010.3f" % 3.1415)


运行结果:

PI=3.141500
PI=3.142
PI=     3.142
PI=3.142
PI=000003.142
PI=+3.142
PI=+00003.142


字符串常用方法:

#字符串常用方法
#1.find. 查找第一个匹配的字符串位置索引,找不到返回-1,可以包含查找起始位置参数
print('chinese people people'.find('peo'))
print('chinese people people'.find('peo',9))
#2.join. split的逆操作,用来在队列中添加元素,队列元素必须是字符串
seq = ['1','2','3','4','5']
sep = '|'
newstr = sep.join(seq)
print(newstr)
#3.lower. 返回字符串的小写字母版
print('HELLO WORLD'.lower())
#4.replace. 字符串替换
print('我|是|中国人'.replace('|',' '))
#5. split. 字符串切割,当不提供分割参数时,程序会把所有空格,如空格,制表符,换行等作为分隔符
print('123,456,789,,,'.split(','))
print('123 456\t789\n123'.split())
#6. strip. 去除字符串两边的空格或指定字符
print('  123456  '.strip())
print(' * 1 23456!x  !'.strip(' *!')) #字符串两边分别从第一个不是去除字符的位置开始保留字符
#7. translate. 替换字符串的某些部分,只处理单个字符,此函数的使用需要用到转换表,也可以成为映射表
str5 = 'hello world'
table = str5.maketrans('abcdefghijklm','AB你好EFGHIJKLM')
print(table)
print(str5.translate(table))


运行结果:

1===================================
8
15
2===================================
1|2|3|4|5
3===================================
hello world
4===================================
我 是 中国人
5===================================
['123', '456', '789', '', '', '']
['123', '456', '789', '123']
6===================================
123456
1 23456!x
7===================================
{97: 65, 98: 66, 99: 20320, 100: 22909, 101: 69, 102: 70, 103: 71, 104: 72, 105: 73, 106: 74, 107: 75, 108: 76, 109: 77}
HELLo worL好


总结:

python与java的方法类似却又不尽相同,python的split函数与java的split相比,python的split截取到最后,而java截取到最后一个不是匹配字符处。如使用两种语言截取“||0||0|||”,根据|截取,python截取结果为[”, ”, ‘0’, ”, ‘0’, ”, ”, ”],java截取结果为[“”, “”, “0”, “”, “0”],且python的split方法可以不提供参数,此时默认以空格,制表符,换行等分割;python的strip方法与java的trim相比,java的功能更精简,只去掉字符串首位的空格,strip却要更强大,支持参数输入进行指定字符删除。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: