python的数据类型:字符串(二)
描述: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的列表。