Python3基礎進階(二)


3.8·Get Length with len()

The len() function counts characters in a string:

>>> letters = 'abcdefg'

>>> len(letters)

7

3.9·Split with split()

Some functions are specific to strings. To use a string function, type thename of the string, a dot, the name of the function, and anyargumentsthat the function needs:

string . function ( arguments )

You can use the built-in stringsplit()function tobreak a string into a listof smaller stringsbased on someseparator.

>>> letters = 'abc,def,ghi'

>>> letters.split(',')

['abc', 'def', 'ghi']

In the preceding example, the string was calledlettersand the string function was called split(), with the single separator argument ','.If you don’t specify a separator, split() uses any sequence of white space characters—newlines, spaces, and tabs.

>>> letters = 'a b c d,ef gh,i'

>>> letters.split()

['a', 'b', 'c', 'd,ef', 'gh,i']

3.10·Combine with join()

Thejoin()function is the opposite of split(): it collapses alistof stringsintoa singlestring.

>>> crypto_list = ['a', 'b', 'c']

>>> crypto_string = '-'.join(crypto_list)

>>> crypto_string

'a-b-c'

3.11·Playing with Strings

Python has a large set ofstring functions. Let’s explore how the most common of them work.

>>> poem = '''All that doth flow we cannot liquid name

Or else would fire and water be the same;

But that is liquid which is moist and wet

Fire that property can never get.

Then 'tis not cold that doth the fire put out

But 'tis the wet that makes it die, no doubt.'''

Does it start with the letters All?

>>> poem.startswith('All')

True

Does it end withThat's all, folks!?

>>> poem.endswith('That\'s all, folks!')

False

let’s find theoffsetof the first occurrence of the wordthein the poem:

>>> poem.find('the')

73

And the offset of the lastthe:

>>> poem.rfind('the')

214

How many times does the three-letter sequencetheoccur?

>>> poem.count('the')

3

Are all of the characters in the poemeither letters or numbers?

>>> poem.isalnum()

False

Nope, there were some punctuation characters.

3.12·Case and Alignment

In this section, we’ll look at some more uses of thebuilt-in string functions.

Our test string is the following:

>>> setup = '...a ..duck goes into a bar...'

>>> setup.strip('.')

'a ..duck goes into a bar'? ? # Remove . sequences from both ends:

Becausestrings are immutable, none of these examples actually changes the setup string. Each example justtakes the value of setup, does something to it, andreturns the result as a new string.

>>> setup = 'a duck goes into a bar...'

>>> setup.capitalize()

'A duck goes into a bar...'

>>> setup.title()

'A Duck Goes Into A Bar...'

>>> setup.upper()

'A DUCK GOES INTO A BAR...'

>>> setup.lower()

'a duck goes into a bar...'

>>> setup = 'a duck goes into a Bar...'

>>> setup.swapcase()

'A DUCK GOES INTO A bAR...'

Now, we’ll work with somelayout alignment functions.

>>> setup = 'a duck goes into a Bar...'

>>> setup.center(30)

'? a duck goes into a Bar...? '

>>> setup = 'a duck goes into a Bar...'

>>> setup.ljust(30)

'a duck goes into a Bar...? ? '

>>> setup.rjust(30)

'? ? a duck goes into a Bar...'

3.13·Substitute with replace()

You usereplace()for simplesubstring substitution. You give it the old substring, the new one, andhow many instances of the old substring to replace. If you omit this final count argument, it replaces all instances.

>>> setup = 'a b c a b c a'

>>> setup.replace('a', 'd', 2)

'd b c d b c a'

Sometimes, you want to ensure that the substring is a whole word, or the beginning of a word, and so on. In those cases, you needregular expressions.

2017.5.27

Chapter 3. Py Filling: Lists, Tuples, Dictionaries, and Sets

In Chapter 2 we started at the bottom with Python’s basic data types:booleans, integers, floats, and strings. If you think of those as atoms, the data structures in this chapter are like molecules.

1.1·Lists and Tuples

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容

  • **2014真題Directions:Read the following text. Choose the be...
    又是夜半驚坐起閱讀 9,916評論 0 23
  • 對未來的真正慷慨,是把一切獻給現在。 前兩天,我忽然發現自己右手上的老年斑不見了,而且皮膚變得細膩,我暗自...
    公主殿下_閱讀 431評論 0 1
  • 自己前兩天寫了《現在開始不算晚》,提醒自己:不要等待,從現在開始做起。但回過頭來再看一遍貓叔的《一切才剛剛開始》,...
    云未遠閱讀 156評論 0 1
  • 這么多年,經歷了太多事,總是在經歷過以后才會懂得。 一如感情,痛過了,才會懂得如何保護自己; - ...
    鳳和先生閱讀 331評論 0 1