str(字符串)常用内置函数

 

列举了几个重要的字符串操作常用内置函数

 

转载请注明出处:http://www.cnblogs.com/dhb5188/p/8555886.html 
参考文献:菜鸟教程http://www.runoob.com/ 、pycharm内置函数库

 

 

replace()

 1 # S.replace(old,new[,count])
 2 # 替换字符串里的字符,old为要被替换的,new为替换的;
 3 # count为指定替换次数,不写替换所有
 4 
 5 s = 'Hello World'
 6  
 7 print (s.replace('o','D'))
 8 print (s.replace('o','D',1))

  输出:

HellD WDrld
HellD World

  

find()

1 # S.find(sub[,start[,end]]) -->int
2 # 查找是否包含sub,start(选填)起始索引,end结束索引
3 # 只会显示左边第一个
4 
5 s = "Hello World"
6 
7 print (s.find('o'))
8 print (s.find('o', 5))
9 print (s.find('o', 1, 7))

  输出:

4
7
4

 

count()

1 # S.count(sub[, start[, end]]) -> int
2 # 用于统计字符串里某个字符出现的次数
3 # sub为子字符串,start起始索引位置,默认0;end结束索引位置(不包含)
4 
5 s = 'Hello World'
6 
7 print (s.count('o'))
8 print (s.count('o', 4, 7))

  输出:

2
1

  

strip()

# S.strip([chars]) -> str
# 移除字符串头尾指定的字符
# 默认移除空格,可指定字符

 

center()

# S.center(width[, fillchar]) -> str
# 指定的宽度 width 居中的字符串,fillchar 为填充的字符,默认为空格
# width为字符串总宽度

s = 'Hello World

print (s.center(50, '-'))

  输出:

-------------------Hello World--------------------

  

split()

# S.split(sep=None, maxsplit=-1) -> list of strings
# 将字符串切片
# sep 指定分隔符,默认为所有的空字符,包括空格、换行(\n)、制表符(\t)等
# maxsplit 指定最大切片次数

s = 'Hello World ding'

print (s.split())
print (s.split(" ",1))

  输出:

['Hello', 'World', 'ding']
['Hello', 'World ding']

  

format()

# 格式化字符串
# 基本语法是通过 {} 和 : 来代替以前的 % 

#用法一
>>>"{} {}".format("hello", "world")    # 不设置指定位置,按默认顺序
'hello world'
 
>>> "{0} {1}".format("hello", "world")  # 设置指定位置
'hello world'
 
>>> "{1} {0} {1}".format("hello", "world")  # 设置指定位置
'world hello world'

#用法二
print("网站名:{name}, 地址 {url}".format(name="电影", url="www.beiwo.tv"))

# 通过字典设置参数
site = {"name": "电影", "url": "www.beiwo.tv"}
print("网站名:{name}, 地址 {url}".format(**site))        #’**‘这里指引用key

# 通过列表索引设置参数
my_list = ['电影', 'www.beiwo.tv']
print("网站名:{0[0]}, 地址 {0[1]}".format(my_list))  # "0" 是必须的

  方法二输出:

网站名:电影, 地址 www.beiwo.tv
网站名:电影, 地址 www.beiwo.tv
网站名:电影, 地址 www.beiwo.tv

  

join()

1 # S.join(iterable) -> str
2 # 将序列中的元素以指定的字符连接生成一个新的字符串
3 # S为连接符
4 # 括号内指定要链接的字符串序列
5 
6 s = 'Hello World'
7 
8 print ('-'.join(s))

  输出:

H-e-l-l-o- -W-o-r-l-d

  

 

转载于:https://www.cnblogs.com/dhb5188/p/8555886.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值