Python學習日記---字串

來源:互聯網
上載者:User

標籤:python   日記   

一、字元序列

  Python字元型變數與其他語言有所不同,因為特殊的命名空間,使得字串是不可直接更改的

 如何指定顯示字串中特定位置的值?如下

>>> helloString = "Hello World"

>>> helloString[0]

‘H‘

>>> helloString[5]

‘ ‘

>>> helloString[-1]

‘d‘

>>> helloString[-5]

‘W‘

由樣本可知,方括弧[]內的值表示特定位置自左向右 0,1,2....自右向左 -1,-2,-3....


二、索引和分區

 Python採用的事半開區間,包含範圍內的起始值,不包含結束值

1.普通的分區和索引

>>> helloString = "Hello World"

>>helloString[:]    #預設值起始位置為0,結束位置為最後元素的後一位置

‘Hello World‘

>>> helloString[2:5]

‘llo‘

>>> helloString[2:-2]

‘llo Wor‘

>>>helloString[-1]   #只有一個參數則用作起始位置,結束位置為預設值

‘d‘


2.擴充分區

 分區還可以加入第三個參數,指定分區的步長,就是從當前字元和下一字元相隔字元數,預設為1

,當步長為負數時,則表示從串尾部往前提取。樣本如下:

>>> digits = "0123456789"

>>> digits[::-1]  #從尾部向前提取,在迴文中使用較多

‘9876543210‘

>>> digits[1::2]   #得到奇數分區

‘13579‘

>>> digits[0::2]  #得到偶數分區

‘02468‘

>>> digits[-2::-2]

‘86420‘

>>> digits[-1::-2]

‘97531‘

3.複製分區

>>> nameOne = "openex"

>>> nameTwo = nameOne[::-1]

>>> id(nameOne),id(nameTwo)

(5647840, 5648064)

>>> nameOne,nameTwo

(‘openex‘, ‘xenepo‘)

    

三、字串操作             

 1.“+” 運算子可用作兩字串串連  “*” 運算子可用作字串的複製

>>> A = "Hello"

>>> B = "World"

>>> A+B

‘HelloWorld‘

>>> A*2+(" "+B)*3

‘HelloHello World World World‘

   

 2.in運算子

 可用於檢測一字串中是否包含一個字串

>>>‘ab‘ in ‘xxxxxabcc‘

True

 3.字串函數和方法

 函數的使用與C差別不大,方法類似於C++的方法概念如helloString.upper().find("A",1,8)


四、字串的格式化輸出

>>>import math

>>> print ("%-10s,%10s\n%-5d,%5d\n%-8.2f,%.4f"%("ABC","ABC",123,123,math.pi,math.pi))

ABC       ,       ABC

123  ,  123

3.14    ,3.1416        

 #類似C語言的printf格式化輸出, %[符號][寬度][.精度]code


五、一個迴文測試樣本:

 不區分大小寫

 無視特殊符號,只比較數字和字母

 

import string

TestString = input("Please input the string for test: ")

TestString = TestString.lower() #將字串中字母變為小寫

junk = string.punctuation+string.whitespace #利用預定義字串,產生特殊符號集合

for char in junk:

    if(char in TestString):

        TestString = TestString.replace(char, "") #字串替換方法,將char換成""

if(TestString == TestString[::-1]):

    print("%s\n%s"%(TestString,TestString[::-1]))

else:

    print("IT‘s not a palindrome\nONE1:%s\nONE2:%s"%(TestString,TestString[::-1]))


Python學習日記---字串

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.