[Python]Sequence

In Python, string objects are immutable. Therefore, any operation on a string, including string concatenation,  produces a new string object, rather than modifying an existing one. concatenating N strings thus involves building and then immediately throwing away each of N-1 intermediate results. Performance is therefore vastly better for operations that build no intermediate results. but rather produce the desired end result at once.

Python's string-formatting operator % is one such operation, particularly suitable when you have a few pieces(e.g., each bound to a different variable) that you want to put together, perhaps with some constant text in addition. Performance is not a major issue for this specific kind of task. However, the % operator also has other potential advantages, when compared to an expression that uses multiple + operations on string. % is more readable, once you get used to it. Also, you don't have to call str on pieces that aren't already strings(e.g., numbers), because the format specifier %s does so implicitly. Another advantage is that you can use format specifiers other than %s, so that, for example, you can control how many significant digits the string form of a floating-point number should display.

What is "a Sequence?"

Python does not have a specific type called sequence, but sequece is still an often-used term in Python. sequence, strictly speaking, means: a container that can be iterated on, to get a finite number of items, one at a time, and that also supports indexing, slicing, and being passed to the built-in functin len(which gives the number of items in a container). Python lists are the "sequence" you 'll meet most often, but there are may others(strings, unicode objects, tuples, array.arrays, etc.).

Often, one does not need indexing, slicing, and len the ability to iterate, one item at a time, suffices. In that case, one should speak of an iterable(or, to focus on the finite number of items issue, a bounded iterable). Iterables that are not sequences include dictionaries(iteration gives the keys of the dictionary, one at a time in arbitrary order), file objects(iteration gives the lines of the text ifle, one at a time), and many more, including iterators and generators. Any iteralbe can be used in a for loop statement and in many equivalent contexts(the for clause of a list comprehension or Python 2.4 generator expression, and also many built-ins such as min, max, zip, sum, str.join, etc.).

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值