Python 之字串學習筆記

來源:互聯網
上載者:User

0X00 如何定義一個字串

Python 不需要定義其實就是這樣的。。在 Python 中的字串通常這麼寫
>>> str1 = 'hello,world'
>>> str2 = "It's work"
>>> str3 = """ Jack:"oh shit" """
str1 的聲明方式是最普通的聲明方式
str2 的聲明方式可以在字串中存在單引號‘
str3 的聲明方式可以在字串中存在雙引號 “ 還能在字串中換行
0X01 拼接字串

>>> str1 = "hello"
>>> str2 = ","
>>> str3 = "world"
>>> print str1 + str2 + str3
    hello,world
注意:
串連的時候加號左右都要是字串,如果是字串加數字就不行了。除非把數字轉成字串格式
0X02 輸入字串

標準輸入就是直接把你輸入的東西寫到代碼裡,甚至可以用變數名
原始輸入就是直接輸入字串,純字串
具體情況可以從下面的 Demo 中看到效果
>>> hello = "hello,world"
>>> str1 = input("what's your name:")   #擷取標準輸入
    hello
>>> str2 = raw_input("what's your name:")   #擷取原始輸入
    "hello"
>>> print str1
    hello,world
>>> print str2
    hello
0X03 字串格式化

學過 C 的能迅速的理解 Python 裡的字串格式化,沒學過 C 的可以快速的理解 Python 裡的字串格式化 +_+
>>> from string import Template
>>> text = Template("1---$a  2---$b   3---$c   4---$$") # $a $b $c 都是字串預留位置,先寫好後賦值
>>> text.substitute(a="hello,", b="world", c="wow")
    '1---hello,  2---world   3---wow   4---$'
#  %s  是字串預留位置,將後面的字串加到前面
>>> print "hello, %s" % ("world")
    hello, world
# %15s  是將字串向前擴充打15位
>>> print "hello, %15s" % ("world")
    hello,           world
>>> print "%15s, world" % ("hello")
    hello, world
# %-15s 是將字串向後擴充到15位
>>> print "%-15s, world" % ("hello")
    hello          , world
0X04 字串處理函數

find 從一個字串中尋找另一個字串,返回最左端索引,找不到就返回 -1

>>> str = "hello,world"
>>> str.find(",")
    5
>>> str = "hello,hello,world,world"
>>> str.find(",", 8, 12)
    11
如果 find 函數返回了 0,並不是沒找到,而是在 0 的位置找到了。畢竟程式員的世界從來都是從 0 開始數數的

join 串連序列中的元素

>>> str1 = ['hello', 'world']
>>> str2 = "---".join(str1)
>>> print str2
    hello---world
注意這裡是 str.join(list) 而不是 list.join(str)

lower 返回字串的全小寫版

>>> str1 = "HELLO,WORLD"
>>> str2 = str1.lower()
>>> print str2
    hello,world
replace 尋找並替換全部

>>> str1 = "my world, my house, my phone"
>>> str2 = str1.replace("my", "your")   #我就這麼把所有東西過戶給了你+_+
>>> print str2
    your world, your house, your phone
split 分割字串

>>> str1 = "hello,world"
>>> str2 = str1.split(",")
>>> print str2
    ['hello', 'world']  #返回了一個列表
strip 去除兩側的東西

strip 預設去除兩側的空格,當然也可以加參數
>>> str1 = "  hello,world  "
>>> str2 = str1.strip() #預設去除空格
>>> print str2
    hello,world
>>> str1 = "aaahello,worldaaa"
>>> str2 = str1.srtip("a")  #加了參數就刪除兩側的參數裡的內容
>>> print str2
    hello,world

聯繫我們

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