Python第三章-字串__Python

來源:互聯網
上載者:User
第三章  字串

3.1 基底字元串操作

Python的字串和元組差不多,是不可以進行改變的,如果想改變值,可以嘗試list序列化之後在進行修改。
{
   website = 'http://www.Python.org';
   website = [-3:] = 'com'; 
   上面操作違法。
}

3.2 字串格式化:精簡版
字串格式化使用字串格式化操作符(這個名字還是很恰當的)即%來實現。
基本用法例子
1.
  >>> format = "Hello, %s. %s enough for ya?";
  >>> values = ('world' ,'Hot');
  >>> print (format % values);
  Hello, world. Hot enough for ya?
2.
  >>> format = "Pi with three decimals: %.3f";
  >>> from math import pi
  >>> print(format % pi)
  Pi with three decimals: 3.142
3.模板字串
  <基本用法>
  >>> from string import Template;
  >>> s = Template('$x. glorious $x!');
  >>> s.substitute(x='slurm')
  'slurm. glorious slurm!'

  <模板字串如果和別的單詞一起,那麼要{x}區分>
  >>> s = Template("It's ${x}tastic!")
  >>> s.substitute(x='slurm')
  "It's slurmtastic!"
  >>>
  <顯示美元字元用兩個$>
  >>> s=Template("Make $$ selling $x!");
  >>> s.substitute(x='slurm')
  'Make $ selling slurm!'

 <除了關鍵字參數之外,還可以使用字典變數提供值/名稱對>
  >>> s = Template('A $thing must never $action.');
  >>> d = {}
  >>> d['thing'] = 'gentleman'
  >>> d['action'] = 'show his socks'
  >>> s.substitute(d)
  'A gentleman must never show his socks.'

  <safe_substitute 在尋找不到的時候不會報錯>
  >>> s = Template('A $x');
  >>> s.substitute(a='x')   這個會報錯,因為尋找不到
  >>> s.safe_substitute(a='x')  不會報錯,並且輸出下面值
  'A $x'

3.3 字串格式化:完整版
  格式化操作符的右運算元可以是任何東西,如果是元組或者映射類型(如字典)那麼字串格式化講會有所不同。
 
注意:
  如果轉換運算式一部分是元組,那麼必須將它用括弧括起來,以避免出錯。
  {
   Ok
   >>> '%s plus %s equals %s' % (1 ,1 ,2)
   '1 plus 1 equals 2'
   Error
   >>> '%s plus %s equals %s' % 1,1,2
   Traceback (most recent call last):
   File "<pyshell#27>", line 1, in <module>'%s plus %s equals %s' % 1,1,2
   TypeError: not enough arguments for format string
   >>> 
  }

基本轉換說明符-(以下描述循序至關重要(就是使用順序))
   (1)%字元:標記轉換說明符的開始。
   (2)轉換標誌(可選): -表示靠左對齊; 
                 +表示在轉換值之前要加上加號或減號
                 “” 正數之前保留空格
                  0  0填充
   3) 最小欄位寬度(可選):轉換後的字串至少應該具有該指定值的寬度。
   如果是*,則寬度會從值元組中讀取。

   (4)點(.) 後跟隨精度值(可選):如果轉換的是實數,精度值就表示出現在小數點後的位元。如果轉換的是字串,那麼該數字就表示最大欄位寬度。如果是*,那麼精度將會從元組中讀出。

   (5)轉換類型
          d,i 帶符號的十進位整數
          o   不帶符號的八進位
          u   不帶符號的十進位
          x,X 十六進位
          e,E  科學計數法
          f,F  十進位浮點型
          g,G
          C     單字元
          r     字串(使用repr轉換任意Python對象)
          s     字串(使用str轉換任意Ptthon對象)


3.3.1簡單轉換
   >>> 'Price of eggs: $%d' %42
   'Price of eggs: $42'
   >>> 'Price of eggs: $%d' %42
   'Price of eggs: $42'
   >>> 'Hexadecimal price of eggs:%x' %42
   'Hexadecimal price of eggs:2a'
   >>> from math import pi
   >>> 'Pi: %f...' %pi
   'Pi: 3.141593...'
   >>> 'Very inexact estimate of pi: %i' %pi
   'Very inexact estimate of pi: 3'
   >>> 'Using str: %s' % 42L  
   SyntaxError: invalid syntax   (我用的3.5 高版本裡買沒有顯示L了)
   >>> 'Using str: %s' % 42
   'Using str: 42'
   >>> 'Using repr: %r' %42
   'Using repr: 42'
   >>> 

3.3.2 欄位寬度和精度

   >>> '%10f' %pi'  

      3.141593'    >>> '%10.2f' %pi
'      3.14'
   >>> '%.2f' %pi
    '3.14'
    >>> '%.2s' %pi
    '3.'
    >>> '%.5s' % 'Guido van Rossum'
    'Guido'
    <長度可以用*代替,然後在元組裡給出>
    >>> '%.*s' %(5,'Guido van Rossum')
    'Guido'

3.3.3 符號,對齊和0填充
     <0填充>
   >>> '%010.2f' %pi
'0000003.14'
   <靠左對齊>
>>> '%-10.2f' %pi
   '3.14      '
     <空格填充>
        >>> print(('% 5d' %10) + '\n' + ('% 5d' % -10))
        10
        -10
 
     <加號或減號>
   >>> print(('%+5d' %10) + '\n' + ('%+5d' % -10))
   +10
   -10  
3.4 字串方法
  字串常量
  {
    string.digits  0~9
    string.letters 所有字母 大小寫
    string.lowercase 所有小寫字母
    string.printable 所有課列印的字元的字串
    string.punctuation 包含所有標點的字串
    string.uppercase   所有大寫字母的字串
   }  
    字串常量(例如string.letters)與地區有區別,其本身取決於Python所配置的語言,如果可以確定自己使用的是ASCII那麼就可以例如這樣 string.ascii_letters

3.4.1 find (找到輸出最左邊,找不到輸出-1)
>>> mark = "123456789123456789"
>>> mark.find("123456")
0
>>> mark.find("aasd")
-1

可接受區間定義   [)
{
>>> subject = "$$$ Get rich now!!! $$$"
>>> subject.find("$$$")
0
>>> subject.find("$$$" ,1)
20
>>> subject.find("!!!" ,0 ,16)
-1
}


3.4.2 join  非常重要的字串方法,它是split方法的逆方法,用來在隊列中添加元素
{
   >>> seq = [1,2,3,4,5]
>>> sep = '+'
>>> sep.join(seq)
Traceback (most recent call last):
 File "<pyshell#2>", line 1, in <module>
sep.join(seq)
TypeError: sequence item 0: expected str instance, int found

>>> seq = ['1' ,'2' ,'3' ,'4' ,'5']
>>> sep.join(seq)
'1+2+3+4+5'

>>> sep
'+'

>>> seq
['1', '2', '3', '4', '5']

>>> dirs = '','usr','bin','env'
>>> '/'.join(dirs)
'/usr/bin/env'

>>> print ('C:' + '\\'.join(dirs))
C:\usr\bin\env
>>> 
}

3.4.3 lower  (title 所有首字母大寫,其他小寫)
     lower方法返回字串的小寫字母片
     {
>>> 'asdaADdasdwDsdw'.lower()
'asdaaddasdwdsdw'
>>> name = 'Gumby'
>>> names = ['gumby' ,'smith' ,'jones']
>>> if name.lower() in names : print ('Fount it!')
Fount it!
>>>
      }
3.4.4 replace替換
{
  >>> "This is a test".replace('is','eez')
  'Theez eez a test'
}

3.4.5  split(jion的逆方法,用來將字串分割成序列)。
    {
>>> '1+2+3+4+5+6'.split('+')
['1', '2', '3', '4', '5', '6']

>>> '/use/dasd/w/ad/we'.split('/')
['', 'use', 'dasd', 'w', 'ad', 'we']

<如果不提供分割符,會把所有空格作為分隔字元>
>>> "using the default ".split()
['using', 'the', 'default']
}
3.4.6 strip 去除字串兩邊的空格(也可以指定去除字元)
{
>>> '  asdasd   '.strip()
'asdasd'

>>> '000asd000asd00012'.strip('012')
'asd000asd'
}  
3.4.7 translate  這3.5已經取消了,這個先不看了。


相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.