描述:split函數用分隔字符str把字符串拆分成若干個子字符串。num指定拆分多少次,若沒有指定次數,則為全部拆分。
返回值:拆分后的子字符串列表(下一次我們將要學習列表)。
例如:
s = 'I am learning python'
list1 = s.split(' ') # list1 = ['I', 'am', 'learning', 'python']
list1 = s.split(' ', 2) # list1 = ['I', 'am', 'learning python']
upper, lower
str_new = upper()
str_new = lower()
描述:把字符串轉成大寫或小寫。
返回值:大小寫轉換后的新字符串。
例如:
s = 'abc'
s1 = s.uppper() # s1 = 'ABC'
s2 = s1.lower() # s2 = 'abc'
strip, lstrip, rstrip
str_new = strip(char=' ')
str_new = rstrip(char=' ')
str_new = lstrip(char=' ')
描述:strip函數用來去除頭或尾部的指定字符,默認是去掉空格。
返回值:返回處理后的新字符串。
例如:
s = ' abc'
s1 = s.lstrip() # s1 = 'abc'
s2 = s1.rstrip('') # s2 = 'abc'
startswith, endswith
boolean = startswith(str, begin=0, end=len(string))
boolean = endswith(str, begin=0, end=len(string))
描述:檢查字符串是否以str開頭或結尾,可以在指定范圍內檢查。
返回值:如果檢查到,返回True,否則返回False。
例如:
s = 'clk_a'
b1 = s.startswith('clk') # b1 = True
s = 'rst_n'
b2 = s.endswith('_n') # s2 = True
format
str_new = '{}{}...'.format(arg1, arg2, ...)
描述:format用來把其它數字、字符串、甚至對象等格式化成字符串。大括號{}用來指定名稱、位置、數字的格式等。
返回值:格式化后的新字符串。
例如:
s = 'I am learning {lang}'.format(lang='python') # s = 'I am learning python'
s = '{0} {1} {0}'.format('face', 'to') # s = 'face to face'
s = '{} {} {}'.format('I', 'love', 'python') # s = 'I love python'
第一種,按名稱替換。
第二種,按位置替換。
第三種,默認按位置替換,也是最常見的替換方式。
是不是有點像verilog的模塊例化?可以按名稱,也可以按位置。
format數字格式化
數字格式化成字符串的規則如下表:

例如:
s = "8'h{:0>2x}".format(15) # s = "8'h0f"
s = '{:.2%}'.format(3 / 9) # s = "33.33%"
可能有童鞋要問了“字符串內置這么多函數,一下也記不住啊?” 所以下面內容非常重要(敲黑板)。
1. 怎么看string還內置其它什么函數?
s = 'abc'
print(dir(s))
dir()是一個內置函數,能夠查看類的所有屬性和方法。結果如下:

2. 那怎么查看具體函數的使用方法呢?
python已經考慮到這個問題了,不需要百度、不需要查看源代碼,只需要調用help()函數。例如:
print(help(s.find))
將打印出下面的內容:

有沒有被python的貼心功能感動呢?
下一次我們將學習python的列表。