字符串的操作:
1.字符串的格式化,格式化语法:
"% s" str1
"%s %s" %(str1,str2)
同样可以使用字典格式化多个值,如print "%(version)s:%(num).1f" % {"version":"version","num":2}
结果为:version:2.0
2.字符串的转义符:
python提供了函数 strip()、lstrip()、rstrip() 去掉字符串中的转义符
#-*-encoding:utf-8-*-
#strip()去掉转义符
word = "\thello world\n"
print "直接输出:",word #直接输出有制表符和换行符
print "strip()后输出:",word.strip() #输出没有制表符和换行符
print "lstrip()后输出:",word.lstrip() #去除了前面的制表符
print "rstrip()后输出:",word.rstrip() #去除了后面的换行符
3.字符串的合并:
一般使用"+"来连接,同时python提供了 函数join() 连接字符串
join()配合列表实现多个字符串的连接
#使用join()连接字符串
strs = ["hello","world","hello ","China "]
result = "".join(strs)
print result #helloworldhello China
print type(result) #<type 'str'>
4.字符串的截取:
由于python内置了序列,所以可以使用索引和切片来获取子串
也可以使用split()来获取
#-*-encoding:utf-8-*-
#使用split()获取子串
sentence = "Bob said: 1, 2, 3, 4"
print "使用空格取子串:",sentence.split()
print "使用逗号取子串:",sentence.split(",")
print "使用两个逗号取子串:",sentence.split(",",2)
#使用空格取子串: ['Bob', 'said:', '1,', '2,', '3,', '4']
#使用逗号取子串: ['Bob said: 1', ' 2', ' 3', ' 4']
#使用两个逗号取子串: ['Bob said: 1', ' 2', ' 3, 4']
字符串连接后,python将分配新的空间给连接后的字符串,源字符串保持不变:
str1 = "a"
print id(str1) #32722656
print id(str1+"b") #39449664
5.字符串的比较
介绍两个方法startswith()和endswith()
word = "hello world"
print "hello" == word[0:5]
print word.startswith("hello")
print word.endswith("ld",6) #从word的结尾到word[6]之间搜索子串"ld",结果为True
print word.endswith("ld",6,10)#从word[6:10]中搜索不到子串"ld"输出False
print word.endswith("ld",6,len(word))#从word[6:len(word]中搜索子串"ld"输出True
6.字符串的反转
代码实例:
#循环输出反转的字符串
def reverse(s):
out = ""
li = list(s)
for i in range(len(li),0,-1):
out += "".join(li[i-1]) #从列表中的最后一个元素开始处理,依次连接到变量out中
return out
print reverse("hello")
print "方法二:"
def reverse2(s):
li = list(s)
li.reverse()
s = "".join(li)
return s
print reverse2("world")
#方法三
print "方法三:"
def reverse3(s):
return s[::-1]
print reverse3("helloworld")
#olleh
#方法二:
#dlrow
#方法三:
#dlrowolleh
7.字符串的查找和替换
查找字符串
find(substring[,start[,end]])从字符串开始查找substring,找到返回第一次在源字符串中的索引,否则返回-1
rfind(substring[,start[,end]])从字符串末尾查找substring,找到返回在源字符串中的索引,否则返回-1
示例:
sentence = "This is a apple."
print sentence.find("a") #8
print sentence.rfind("a") #10
replace(old,new [,max])
old表示将被替换的字符串
new表示替换old的字符串
参数max表示使用new 替换old的次数
参数返回一个新的字符串,如果子串old不在源字符串中,则函数返回源字符串的值。
8.字符串与日期的转换
时间转为字符串
strftime()
字符串到时间的转换
strptime(),从字符串到时间的转换需要进行两次转换,步骤如下:
①调用函数strptime()把字符串转为一个元组,进行第一次转换
②把表示时间的元组赋值给表示年、月、日的3个变量
③把表示年月日的3个变量传递给函数datetime(),进行第2次转换
示例如下:
#-*-encoding:utf-8-*-
import time,datetime
#时间到字符串的转换
print time.strftime("%Y-%m-%d %X",time.localtime())
#2019-11-16 21:24:31
#字符串到时间的转换
t = time.strptime("2019-11-16","%Y-%m-%d")
y,m,d = t[0:3]
print datetime.datetime(y,m,d)
#2019-11-16 00:00:00