一、字符串的创建
test = str() / "" test = str("licheng") / "licheng"
- 无参数,创建空字符串
- 一个参数,创建普通字符串
- 两个参数,int(字节,编码)
二、字符串的常用方法
#capitalize():字符串首字符大写 string = 'this is a string.' new_str = string.capitalize() print(new_str) #输出:This is a string.#center(width, fillchar=None):将字符串放在中间,在指定长度下,首尾以指定字符填充 string = 'this is a string.' new_str = string.center(30,'*') print(new_str) #输出:******this is a string.*******#count(sub, start=None, end=None):计算字符串中某字符的数量 string = 'this is a string.' new_str = string.count('i') print(new_str) #输出:3#decode/encode(encoding=None, errors=None):解码/解码 string = 'this is a string.' new_str = string.decode() new_str = string.encode() print(new_str)#endswith(self, suffix, start=None, end=None):判断是否以某字符结尾 string = 'this is a string.' new_str = string.endswith('ing.') print(new_str) #输出:True#find(self, sub, start=None, end=None):在字符串中寻找指定字符的位置 string = 'this is a string.' new_str = string.find('a') #找的到的情况 print(new_str) #输出:8 new_str = string.find('xx') #找不到的情况返回-1 print(new_str) #输出:-1#index(self, sub, start=None, end=None):;类似find string = 'this is a string.' new_str = string.index('a') #找的到的情况 print(new_str) #输出:8 new_str = string.index('xx') #找不到的情况,程序报错 print(new_str) #输出:程序运行报错,ValueError: substring not found#isalnum(self):判断字符串中是否都是数字和字母,如果是则返回True,否则返回False string = 'My name is yue,my age is 18.' new_str = string.isalnum() print(new_str) #输出:False string = 'haha18121314lala' new_str = string.isalnum() print(new_str) #输出:True#isalpha(self):判断字符串中是否都是字母,如果是则返回True,否则返回False string = 'abcdefg' new_str = string.isalpha() print(new_str) #输出:True string = 'my name is yue' new_str = string.isalpha() #字母中间带空格、特殊字符都不行 print(new_str) #输出:False# isdigit(self):判断字符串中是否都是数字,如果是则返回True,否则返回False string = '1234567890' new_str = string.isdigit() print(new_str) #输出:True string = 'haha123lala' new_str = string.isdigit() #中间带空格、特殊字符都不行 print(new_str) #输出:False# islower(self):判断字符串中的字母是否都是小写,如果是则返回True,否则返回False string = 'my name is yue,my age is 18.' new_str = string.islower() print(new_str) #输出:True string = 'My name is Yue,my age is 18.' new_str = string.islower() print(new_str) #输出:False# isupper(self):检测字符串中所有的字母是否都为大写。 string = 'MY NAME IS YUE.' new_str = string.isupper() print(new_str) #输出:True string = 'My name is Yue.' new_str = string.isupper() print(new_str) #输出:False# join(self, iterable):将序列中的元素以指定的字符连接生成一个新的字符串。 string = ("haha","lala","ohoh") str = "-" print(str.join(string)) #输出:haha-lala-ohoh# lower(self):转换字符串中所有大写字符为小写。 string = "My Name is YUE." print(string.lower()) # 输出:my name is yue.# lstrip(self, chars=None):截掉字符串左边的空格或指定字符。 string = " My Name is YUE." print(string.lstrip()) #输出:My Name is YUE. string = "My Name is YUE." print(string.lstrip('My')) #输出: Name is YUE.#replace(self, old, new, count=None):把字符串中的 old(旧字符串) 替换成 new(新字符串),如果指定第三个参数max,则替换不超过 max 次。 string = "My name is yue." print(string.replace("yue","ying")) #输出:My name is ying.# rfind(self, sub, start=None, end=None):返回字符串最后一次出现的位置,如果没有匹配项则返回-1。 string = "My name is yue." print(string.rfind('is')) #输出:8 string = "My name is yue." print(string.rfind('XXX')) #输出:-1# split(self, sep=None, maxsplit=None):通过指定分隔符对字符串进行切片。 string = "haha lala gege" print(string.split(' ')) #输出:['haha', 'lala', 'gege'] print(string.split(' ', 1 )) #输出: ['haha', 'lala gege']# rsplit(self, sep=None, maxsplit=None):通过指定分隔符对字符串从右进行切片。 string = "haha lala gege" print(string.rsplit(' ')) #输出:['haha', 'lala', 'gege'] print(string.rsplit(' ', 1 )) #输出: ['haha lala', 'gege']# rstrip(self, chars=None):删除 string 字符串末尾的指定字符(默认为空格). string = " My name is yue. " print(string.rstrip()) #输出: My name is yue.# strip(self, chars=None):移除字符串头尾指定的字符(默认为空格)。 string = " My name is yue. " print(string.strip()) #输出:My name is yue.# upper(self):将字符串中的小写字母转为大写字母。 string = "my name is yue,my age is 18." print(string.upper()) #输出:MY NAME IS YUE,MY AGE IS 18.
str源码
三、字符串的公共功能
- 索引(只能取一个元素)
- 切片(取多个元素)
- 长度(len)
- python2:按字节算长度
- python3:按字符算长度
- for循环(同长度的版本循环单位)
四、字符与字节的转换
# 将gbk编码的字符转化为字节 s = "李程" b = bytes(s, encoding="gbk") type(b) 输出为字节类型# 将字节转化为字符 c = str(b, encoding="gbk")
五、字符串格式化
Python的字符串格式化有两种方式: 百分号方式、format方式
百分号的方式相对来说比较老,而format方式则是比较先进的方式,企图替换古老的方式,目前两者并存。
1、百分号方式
%[(name)][flags][width].[precision]typecode
参数详解
常用格式化:
tpl = "i am %s" % "spark"tpl = "i am %s age %d" % ("spark", 18)tpl = "i am %(name)s age %(age)d" % {"name": "spark", "age": 18}tpl = "percent %.2f" % 99.97623tpl = "i am %(pp).2f" % {"pp": 123.425556, }tpl = "i am %.2f %%" % {"pp": 123.425556, }
2、Format方式
[[fill]align][sign][#][0][width][,][.precision][type]
参数详解
常用格式化:
1 tpl = "i am {}, age {}, {}".format("seven", 18, 'alex')2 3 tpl = "i am {}, age {}, {}".format(*["seven", 18, 'alex'])4 5 tpl = "i am {0}, age {1}, really {0}".format("seven", 18)6 7 tpl = "i am {0}, age {1}, really {0}".format(*["seven", 18])8 9 tpl = "i am {name}, age {age}, really {name}".format(name="seven", age=18) 10 11 tpl = "i am {name}, age {age}, really {name}".format(**{"name": "seven", "age": 18}) 12 13 tpl = "i am {0[0]}, age {0[1]}, really {0[2]}".format([1, 2, 3], [11, 22, 33]) 14 15 tpl = "i am {:s}, age {:d}, money {:f}".format("seven", 18, 88888.1) 16 17 tpl = "i am {:s}, age {:d}".format(*["seven", 18]) 18 19 tpl = "i am {name:s}, age {age:d}".format(name="seven", age=18) 20 21 tpl = "i am {name:s}, age {age:d}".format(**{"name": "seven", "age": 18}) 22 23 tpl = "numbers: {:b},{:o},{:d},{:x},{:X}, {:%}".format(15, 15, 15, 15, 15, 15.87623, 2) 24 25 tpl = "numbers: {:b},{:o},{:d},{:x},{:X}, {:%}".format(15, 15, 15, 15, 15, 15.87623, 2) 26 27 tpl = "numbers: {0:b},{0:o},{0:d},{0:x},{0:X}, {0:%}".format(15) 28 29 tpl = "numbers: {num:b},{num:o},{num:d},{num:x},{num:X}, {num:%}".format(num=15)
更多格式化操作:https://docs.python.org/3/library/string.html