字串类别内建许多函式,
只要是Python字串就自动拥有这些函式,
以下介绍常用的内建函式。
# input
a = '君莫惜金缕衣,劝君惜取少年时。花开堪折直须折,莫待无花空折枝!'
b = a.split(',')
print(b)
#output
['君莫惜金缕衣', '劝君惜取少年时', '花开堪折直须折', '莫待无花空折枝!']
#intput
a = ['君莫惜金缕衣', '劝君惜取少年时', '花开堪折直须折', '莫待无花空折枝!']
b = ','.join(a)
print(b)
#output
君莫惜金缕衣,劝君惜取少年时,花开堪折直须折,莫待无花空折枝!
#input
a = '君莫惜金缕衣,劝君惜取少年时,花开堪折直须折,莫待无花空折枝!'
b = a.replace('君','A')
print(b)
#output
A莫惜金缕衣,劝A惜取少年时,花开堪折直须折,莫待无花空折枝!
#input
a = '君莫惜金缕衣,劝君惜取少年时,花开堪折直须折,莫待无花空折枝!'
print(a.find('少年'))
#output
11 #「要找的字串」的位置值
检查字串是否已「要找的字串」开头,若是则回传True,否则回传False
#input
a = '君莫惜金缕衣,劝君惜取少年时,花开堪折直须折,莫待无花空折枝!'
print(a.startswith('君莫'))
print(a.startswith('折枝'))
#output
True
False
检查字串是否已「要找的字串」结尾,若是则回传True,否则回传False
#input
a = '君莫惜金缕衣,劝君惜取少年时,花开堪折直须折,莫待无花空折枝!'
print(a.startswith('君莫'))
print(a.startswith('折枝'))
#output
False
True
#intput
a = '君莫惜金缕衣,劝君惜取少年时,花开堪折直须折,莫待无花空折枝!'
print(a.count('折'))
#output
3
保留长度为「数值」字串空间,将字串置中摆放。
#input
a = '君莫惜金缕衣'
print(a.center(10))
#output
君莫惜金缕衣
保留长度为「数值」字串空间,将字串靠右摆放。
#intput
a = '君莫惜金缕衣'
print(a.rjust(10))
#output
君莫惜金缕衣
保留长度为「数值」字串空间,将字串靠左摆放。
#intput
a = '君莫惜金缕衣'
print(a.ljust(10))
#output
君莫惜金缕衣
将英文字串的字首转成大写
#intput
a = 'have a nice day'
print(a.capitalize())
#output
Have a nice day
将英文字串的每个单字字首转成大写
#intput
a = 'have a nice day'
print(a.title())
#output
Have A Nice Day
将英文字串的大写字母转成小写字母,小写字母转成大写字母
#intput
a = 'Have A Nice Day'
print(a.swapcase())
#output
hAVE a nICE dAY
将英文字串的所有字母转成大写字母
#intput
a = 'Have A Nice Day'
print(a.upper())
#output
HAVE A NICE DAY
#intput
a = 'Have A Nice Day'
print(a.lower())
#output
have a nice day
将字串左侧补0直到宽度为width为止
#intput
a = '1234'
print(a.zfill(5))
#output
0001234
字串的左右两边删除chars所指定的字元,
字元可以不只一个,
若没有指定预设移除空白字元
#intput
a = '1234'
print(a.zfill(5))
#output
0001234
字串的左右两边删除chars所指定的字元,
字元可以不只一个,
若没有指定预设移除空白字元
#intput
a = 'hello,smith'
print(a.strip('h'))
print(a.strip())
#output
ello,smit
hello,smith
字串的右边删除chars所指定的字元,
字元可以不只一个,
若没有指定预设移除空白字元
#intput
a = 'hello,smith'
print(a.rstrip('h'))
#output
hello,smit
字串的左边删除chars所指定的字元,
字元可以不只一个,
若没有指定预设移除空白字元
#intput
a = 'hello,smith'
print(a.lstrip('h'))
#output
ello,smith
以上是今天的字串内建函式,
我想跟各位程序新手说一个观念,
会写程序不用像大考一样凭脑袋记忆写出来,
要会善用网路上的资源,
很多科技公司面试,
当主考官考你程序设计时,
有些会提供你网路查询,
有些甚至只看你的解题想法、逻辑是否清晰,
所以会善用网路才能帮助你的编程能力更加进步,
字串的内建函式固然很多,
但你只要知道功能是什麽,
在写程序时上网查能找到且执行成功,
这就是一个好的进展 !!
明天会提供例题给大家练习,
我们一起加油~~
好消息,我找到一个贴文跟一个影片,所以逛头盔这件事可以延後一点做: How to use Unity...
同时开启多个浏览器 有时候可能需要多个浏览器来进行测试, 譬如说用多个浏览器来测试WebSocket...
今天要学习的是观察者模式,它主要的作用是设定一个订阅机制,当被订阅的物件有发生事件时就会去通知所...
Metrics - 观察系统的健康指标 系列文章 (1/6) - Metrics 与 Metricb...
注:发文日和截图的日期不一定是同一天,所以价格计算上和当日不同,是很正常的。 声明:这一系列文章并无...