[分享] Python3基础Lesson5
583 查看
0 回复
 楼主 | 发布于 2018-03-28 | 只看楼主
分享到:

1. 字符串分片与步距

分片操作符有3种语法格式:

seq[start]

seq[start:end]

seq[start:end:step]

start、end和step都必须是整数。例如:

s = "The waxwork man"
print(s[5:9:1])

输出结果:

axwo


如果需要倒取字符则可以

s = "The waxwork man"
print(s[::-1])

输出结果:

nam krowxaw ehT


2. 字符串的复制:*

使用*可以实现字符串的复制

s = "The waxwork man"
s = s * 5

输入结果:

The waxwork manThe waxwork manThe waxwork manThe waxwork manThe waxwork man

使用str.find()或者str.index()可以查找内容在字符串中的位置,如:

s = "The waxwork man"
a = s.find("wax")
print(a)

输出结果:

4


3. str.format()方法进行字符串格式化

str.format()提供了灵活而强大的创建字符串的途径。此方法会返回一个新的字符串,在新的字符串中,原字符串的替换字段被适当格式化后的参数所代替,如:

s = "The novel '{0}' was published in {1}"
a = s.format("Hard Times", 1854)
print(a)

输出结果:

The novel 'Hard Times' was published in 1854

字段名可以引用集合数据类型,比如列表。这样我们可以包含一个索引来标示特定的数据项:

stock = ["paper", "envelopes", "notebooks", "pens"]
str = "We have {0[1]} and {0[2]} in stock"
print(str.format(stock))

输出结果:

We have envelopes and notebooks in stock

字典对象(key-value)也可以用于str.format()方法:

d = dict(animal = "elephant", weight = 12000)
str = "The {0[animal]} weights {0[weight]}kg"
print(str.format(d))

输出结果:

The elephant weights 12000kg


NEXT 。。。

(0 ) (0 )
回复 举报
  • 发表回复
    0/3000





    举报

    请选择举报类别

    • 广告垃圾
    • 违规内容
    • 恶意灌水
    • 重复发帖

    全部板块

    返回顶部