1. 程式人生 > >python學習筆記:string的列印

python學習筆記:string的列印

(一)換行列印:

print("""abc
def""")

#等價於:
print("abc")
print("def")

#輸出: 
#abc
#def

(二)索引特定位置字元:

           即引用字串s中特定位置字元。從0開始,如果為負數X等價於len(s)-X

s="abcdefg"
print(s[0])           #a
print(s[1])           #b
print(s[2])           #c
print("------")       
print(s[len(s)-1])    #g
print(s[len(s)])      #error
print(s[-1])          #==s[len(s)-1]    g

(三)擷取一段字串:

          使用s[ : ]:擷取字串中一段字元,遵循左閉右開原則,從0開始,到X-1結束。

s = "abcdefgh"
print(s)
#a range of characters   取一段字元
print(s[0:3])               #abc
print(s[1:3])               #bc
print("-----------")
print(s[2:3])               #c
print(s[3:3])               #None

#with default parameters 預設引數
print(s[3:])                #defgh
print(s[:3])                #abc
print(s[:])                 #abcdefgh
print("-----------")        

#with a step parameter   步長  
print("This is not as common, but perfectly ok.")
print(s[1:7:2])             #bdf    2是步長,即輸出1、1+2、1+2+2 (1+2+2+2=7超出範圍)
print(s[1:7:3])             #be     3是步長,即輸出1、1+3  (1+3+3=7超出範圍)

(三)翻轉字串:

           reversing:s[ : : -1],最好的方式寫自定義函式,清楚明瞭

s = "abcdefgh"

print("This works, but is confusing:")
print(s[::-1])

print("This also works, but is still confusing:")
print("".join(reversed(s)))

print("Best way: write your own reverseString() function:")

def reverseString(s):
    return s[::-1]

print(reverseString(s)) # crystal clear!

(四)引用常量:

import string
print(string.ascii_letters)   # abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ
print(string.ascii_lowercase) # abcdefghijklmnopqrstuvwxyz
print("-----------")
print(string.ascii_uppercase) # ABCDEFGHIJKLMNOPQRSTUVWXYZ
print(string.digits)          # 0123456789
print("-----------")
print(string.punctuation)     # '!"#$%&\'()*+,-./:;<=>[email protected][\\]^_`{|}~'
print(string.printable)       # digits + letters + punctuation + whitespace
print("-----------")
print(string.whitespace)      # space + tab + linefeed + return + ...

☆☆關於string模組(形式:string.)VS. python內建函式(形式:S.method(XX))

早期,使用import string 可引用專門的string模組,但後來由於眾多的python使用者的建議,從python2.0開始,string方法改為用S.method()的形式呼叫,只要S是一個字串物件就可以這樣使用,而不用import。

為了保持向後相容,現在的python中仍然保留了一個string的module,其中定義的方法與S.method()是相同的,這些方法都最後都指向了用S.method()呼叫的函式。

要注意,S.method()能呼叫的方法比string的module中的多,比如isdigit()、istitle()等就只能用S.method()的方式呼叫。

(五)字串連線的“+”和“*”:

print("abc"+"def")      #abcdef
print("abc"*3)          #abcabcabc

(六)判斷:

1、字串中是否存在某個字串 “in”:

print("ring" in "strings")     #True
print("wow" in "amazing!")     #False
print("Yes" in "yes!")         #False
print("" in "No way!")         #True

2、S.isalnum()或者str.isalnum(S):判斷字串s是否全部由字母和數字組成,返回True/False  

3、S.isalpha()或者str.isalpha(S):判斷字串s是否只由字母組成,返回True/False

4、S.isdigit()或者isdigit(S):判斷字串s是否只由數字組成,返回True/False

5、S.isupper()或者str.isupper(S):判斷字串s是否全部為大寫字母,返回True/False

6、S.islower()或者str.islower(S):判斷字串s是否全部為小寫字母,返回True/False

7、S.isspace()或者str.isspace(S):判斷字串s是否只由空格組成,返回True/False

# Run this code to see a table of isX() behaviors
def p(test):
    print("True     " if test else "False    ", end="")
def printRow(s):
    print(" " + s + "  ", end="")
    p(s.isalnum())
    p(s.isalpha())
    p(s.isdigit())
    p(s.islower())
    p(s.isspace())
    p(s.isupper())
    print()
def printTable():
    print("  s   isalnum  isalpha  isdigit  islower  isspace  isupper")
    for s in "ABCD,ABcd,abcd,ab12,1234,    ,AB?!".split(","):
        printRow(s)
printTable()
上述程式碼輸出: 
 s   isalnum  isalpha  isdigit  islower  isspace  isupper
 ABCD  True     True     False    False    False    True     
 ABcd  True     True     False    False    False    False    
 abcd  True     True     False    True     False    False    
 ab12  True     False    False    True     False    False    
 1234  True     False    True     False    False    False    
       False    False    False    False    True     False    
 AB?!  False    False    False    False    False    True

(七)編輯字串:

1、s.lower():將字串s中的大寫字母轉換為小寫字母,數字不變

2、s.upper():將字串s中的小寫字母轉換為大寫字母,數字不變

3、s.replace(A,B,N):將字串s中第N個A替換為B,並返回新的字串,如N=0,則全部替換

4、s.strip(XX):將字串s頭尾XX部分移除,並返回新的字串(不是s的任意部分)

print("This is nice. Yes!".lower())
print("So is this? Sure!!".upper())
print("   Strip removes leading and trailing whitespace only    ".strip())
print("This is nice.  Really nice.".replace("nice", "sweet"))
print("This is nice.  Really nice.".replace("nice", "sweet", 1)) # count = 1

print("----------------")
s = "This is so so fun!"
t = s.replace("so ", "")
print(t)
print(s) # note that s is unmodified (strings are immutable!)

(八)子字串

1、s.count(sub, start=num1,end=num2):統計字串中子字串sub出現的次數,start(起始位置)、end(結束位置)可缺                                                                        省

2、s.startswith(sub,start=num1,end=num2):檢查字串[start,end]是否是以指定子字串sub開頭

3、s.endswith(suffix,start=num1,end=num2):檢查字串[start,end]是否是以指定子字串suffix結尾

4、s.find(sub):檢查字串str是否有子字串sub,返回子字串sub的起始位置

5、s.index(sub):返回字串str中子字串sub的起始位置

print("This is a history test".count("is")) # 3
print("This IS a history test".count("is")) # 2
print("-------")
print("Dogs and cats!".startswith("Do"))    # True
print("Dogs and cats!".startswith("Don't")) # False
print("-------")
print("Dogs and cats!".endswith("!"))       # True
print("Dogs and cats!".endswith("rats!"))   # False
print("-------")
print("Dogs and cats!".find("and"))         # 5
print("Dogs and cats!".find("or"))          # -1
print("-------")
print("Dogs and cats!".index("and"))        # 5
print("Dogs and cats!".index("or"))         # crash!