Python的基本数据类型主要有6种,分别是number(数字),字符串(string),列表(list),集合(set),元组(tuple),字典(dictionary)。
字符串要用单引号或者双引号括起来,访问字符串时要用([ ])方括号,语法如下:变量[头下标:尾下标],字符串从左往右,下标最小索引值从0开始,-1为末尾的开始位置。
栗子:
str = "hello world!" print(str)#打印string print(str[0:-1])#打印第一个到倒数第二个的所有字符 print(str[-1])#打印字符串最后一个 print(str[2:5])#打印第三个到第五个字符 print(str[2:])#打印第三个后所有字符 print(str * 3)#打印字符串3遍 output: hello world! hello world ! llo llo world! hello world!hello world!hello world!常用的关于字符串的内置方法:
count(sub[,start[,end]])方法查找sub参数在string中出现的次数,可选参数start和end表示查找的范围:
str1 = "members of the Communist Party of China"
str1.count('f')
str1.count('f', 0, 10)
output:
2
1
find(sub[,start[,end]])方法查找sub参数在字符串中第一次出现的位置,如果找到,则返回位置索引值;如果找不到,则返回-1。rfind(sub[,start[,end]])方法查找sub参数在字符串中最后一次出现的位置,如果找到,则返回位置索引值。
str1 = "members of the Communist Party of China"
str1.find('f')
str1.find('f', 0, 5)
str1.rfind('f')
otput:
9
-1
32
replace(old,new[,count])方法将string中old参数替换成new参数。
str = "i love her"
str.replace("her", "you")
output:
'i love you'
split(sep=None, maxsplit=-1)方法用于拆分字符串。
str = "肖申克的救赎/1992year/9.6分/美国"
str.split("/")
output:
['肖申克的救赎', '1992year', '9.6分', '美国']
join(iterable)方法用于拼接字符串,以字符串为分隔符。
countries = ["美国", "中国", "雅典", "日本"] '--'.join(countries) output: '美国--中国--雅典--日本'格式化 format()方法
接收位置参数和关键字参数。
"{0} love {1}".format("i", "you")
output:
'i love you'
{0} {1}与位置有关,依次被format()的两个参数替换,那么,我们称format()的两个参数为位置参数。
!!!注意format后面是圆括号,不是花括号。另外format前面有一点。
"{a} love {b}".format(b="you", a="i")
output:
'i love you'
{a} {b}相当于两个目标标签,format()将参数中等值的字符串替换进去,这就是关键字参数。
!!!注意位置参数和关键字参数可以混合使用,但是,位置参数必须在关键字参数之前。
"{a} love {0}".format(a="i", "you")
output:
SyntaxError: positional argument follows keyword argument
格式化操作符:%
栗子:
str1 = "一支穿云箭----------" str2 = "千军万马来相见" "%s%s" % (str1, str2) output: '一支穿云箭----------千军万马来相见'
关于字符串还有很多吗可能想不到的秘密,等待你的发掘……



