【python】常见的string的操作

转为大写字母

claim = "Pluto is a planet!"
claim.upper()
>>> 'PLUTO IS A PLANET!'

转为小写字母

# all lowercase
claim.lower()
>>> 'pluto is a planet!'

寻找指定字符串所在的索引

claim.index('plan')
>>> 11

claim.startswith(planet)
>>> True
claim.endswith('dwarf planet')
>>> False
words = claim.split()
words
>>>  ['Pluto', 'is', 'a', 'planet!']
datestr = '1956-01-31'
year, month, day = datestr.split('-')
/'.join([month, day, year])
>>> '01/31/1956'
' 👏 '.join([word.upper() for word in words])
>>> 'PLUTO 👏 IS 👏 A 👏 PLANET!'
planet + ', we miss you.'
>>> 'Pluto, we miss you.'
position = 9
planet + ", you'll always be the " + str(position) + "th planet to me."
>>> "Pluto, you'll always be the 9th planet to me."

.format()的一些用法

# We call .format() on a "format string", where the Python values we want to insert are represented with {} placeholders.
"{}, you'll always be the {}th planet to me.".format(planet, position)
>>> "Pluto, you'll always be the 9th planet to me."


pluto_mass = 1.303 * 10**22
earth_mass = 5.9722 * 10**24
population = 52910390
# 2 decimal points   3 decimal points, format as percent separate with commas
"{} weighs about {:.2} kilograms ({:.3%} of Earth's mass). It is home to {:,} Plutonians.".format(
    planet, pluto_mass, pluto_mass / earth_mass, population,
)
>>> "Pluto weighs about 1.3e+22 kilograms (0.218% of Earth's mass). It is home to 52,910,390 Plutonians."


s = """Pluto's a {0}.
No, it's a {1}.
{0}!
{1}!""".format('planet', 'dwarf planet')
print(s)
>>>Pluto's a planet.
No, it's a dwarf planet.
planet!
dwarf planet!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值