planet = "Pluto"
planety[0] # 字符串中第1个字符,索引从0开始
# 'p'
planet[-3:] # 从第-3个开始到最后
# 'uto'
len(planet) # 打印字符串的长度
# 5
[char+'!' for char in planet] # 循环并修改字符串为列表格式
# ['P!','l!','u!','t!','o!']
# 但它们与列表的一个主要区别是它们是不可变的。我们不能修改它们
planet[0] = 'B'
# TypeError
upper()
全部大写 claim = "Pluto is a planet!"
claim.upper()
# 'PLUTO IS A PLANET!'
lower()
全部小写 claim.lower()
# 'pluto is a planet!'
index()
返回被搜索字符串第一个字符的索引 claim.index('plan')
# 11
.split()
和 .join()
str.split()
words = claim.split()
words
# ['Pluto', 'is', 'a', 'planet!']
在空格之外的地方进行分割:
datestr = '1956-01-31'
year, month, day = datestr.split('-')
str.join()
'/'.join([month, day, year])
# '01/31/1956'
'.'.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 " + position + "th planet to me."
# TypeError
format()
模板字符串 "{}, you'll always be the {}th planet to me.".format(planet, position) # 可以凭借int类型的变量
# "Pluto, you'll always be the 9th planet to me."
# 可以按索引引用format()参数,从0开始
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!