美文网首页
Python字符串操作

Python字符串操作

作者: yannhuang | 来源:发表于2017-12-13 11:47 被阅读8次

一、字符串格式化

Python有三种字符串格式化方法:百分号方式,format方式,模板方式

1、百分号方式
#使用单个字符串
print ("i am %s" % "yann")

#使用元组
print ("hello, %s ! I am %s" % ('world', 'yann'))

#使用字典
print ("i am %(name)s age %(age)d" % {"name": "alex", "age": 18})

#使用浮点数
print ("percent %.2f" % 99.97623)
2、format方式
#按顺序
print("i am {}, age {}, {}".format("seven", 18, 'alex'))

#按占位符
print("i am {0}, age {1}, really {0}".format("seven", 18))

#使用字典
print("i am {name}, age {age}, really {name}".format(name="seven", age=18))

#使用转换字符
print("i am {:s}, age {:d}, money {:f}".format("seven", 18, 88888.1))
3、模版方式

模版方式需要导入string模块中的 Tmplate函数

from string import Template

使用示例如下:

from  string  import  Template

#使用字符
s = Template('$x, my name is $x  $y')
s.substitute(x='yann',y='huang')

#替换字段是单词的一部分
s = Template('It is ${x}sastic!')
s.substitute(x='slurm')

#使用字典
s = Template('A $thing must never $action')
d = {}
d['thing'] = 'gentleman'
d['action'] = 'show his socks'
s.substitute(d)

详细参考:https://www.cnblogs.com/nulige/p/6115793.html

二、字符串操作

1、find

find方法可以在一个较长的字符串中查找子字符串,返回子字符串所在位置的最左端的索引,如果没有找到就返回 -1

title = "my name is yann!"
title.find('name')
output: 3

类似方法:rfind, index, rindex, count, startwith, endswith

2、join

按指定符号把字符串序列连接在一起,注意队列元素必须是字符串

seq = ['1', '2', '3', '4', '5']
sep = '+'
sep.join(seq)

output: '1+2+3+4+5'

类似方法:split

3、lower

lower 返回字符串的小写字母版

print("MY NAME IS YANN".lower())
output: my name is yann

#如果希望返回的是首字母大写,其他字母小写的字符串,则用title
print("MY NAME IS YANN".title())
output: My Name Is Yann

类似方法:islower, capitalize, swapcase, title, upper, isupper

4、replace

返回某字符串的所有匹配项都被替换之后得到的字符串

"this is a test".replace('is', 'eez')
output: 'theez eez a test'

与 replace 相关的是 translate,支持使用转换表,替换多个字符串

5、split

把字符串分割成序列,如果不提供任何分隔符,默认使用空格

"1+2+3+4+5".split('+')
output: ['1', '2', '3', '4', '5']

相关方法:rsplit, splitlines

6、strip

返回去除两侧(不包括内部)空格的字符串,如果需要去除指定字符,则将它们作为参数即可

"  my name is yann  ".strip()
output: 'my name is yann'

"***my name is yann*".strip('*')
output: 'my name is yann'

相关方法:lstrip, rstrip

相关文章

网友评论

      本文标题:Python字符串操作

      本文链接:https://www.haomeiwen.com/subject/apkaixtx.html