程序员

Python学习笔记-字符串及操作

2017-12-03  本文已影响0人  vincentgemini

每一门语言都离不开字符串以及字符串操作,Python也为字符串定义了很多函数。

1、字符串切片

sub = string[起始位置:结束为止:步长]

2、find查找前缀,rfind查找后缀

string = "http://www.jianshu.com/p/2cb6159d3f13"
findIndex = string.find(":")
if findIndex == -1:
    print("%s 没有找到的协议"%string)
else:
    print("%s 找到的协议是:%s"%(string,string[0:findIndex]))

fileName = "/test/A/a.text"
findIndex = fileName.rfind(".")
if findIndex == -1:
    print("文件%s 没有找到扩展名"%fileName)
else:
    print("文件%s 找到的扩展名是:%s"%(fileName, fileName[findIndex+1:]))

3、如果使用index和rindex,需要注意,如果没有子字符串,则会出现异常

string = "http://www.jianshu.com/p/2cb6159d3f13"
print("%s 使用的协议是:%s"%(string, string[0:string.index(":")]))
print("%s 使用的协议是:%s"%(string, string[0:string.rindex(":")]))

4、count测试字符串重复出现的次数

5、replace替换字符串中的子字符串

6、split分隔字符串

string = "http://www.jianshu.com/p/2cb6159d3f13"
print(string.split("://"))

7、title:字符串每个单词首字母大写和capitalize:字符串首字母大写

message = "hello world! Ha Ha ha"
temp1 = message.title()
temp2 = message.capitalize()
print((message, temp1, temp2))

8、startswith和endswith

判断是否以某个字符串开头或结尾。

string = "http://www.jianshu.com/p/2cb6159d3f13"
if string.startswith("http"):
    print("字符串是以:http开头的");

fileName = "/test/A/a.text"
if fileName.endswith("text"):
    print("字符串是以:text结尾的");

9、lower和upper

将字符串以小写或大写形式输出。

message = "hello world! Ha Ha ha"
newMessage1 = message.lower()
newMessage2 = message.upper()
print("%s转换后为:%s====%s"%(message, newMessage1, newMessage2))

10、ljust、rjust和center

给定字符串宽度,输出按照左对齐,右对齐和中间对齐符串。

message = "hello world! Ha Ha ha"
print(message.ljust(50))
print(message.rjust(50))
print(message.center(50))

11、lstrip、rstrip和strip

输出去掉字符串前、后或者前后空格的字符串。

message = "   hello world! Ha Ha ha  "
print(message.lstrip(" "))
print(message.rstrip(" "))
print(message.strip(" "))

12、partition和rpartition

将字符串分成三部分,区别与split。

string = "http://www.jianshu.com/p/2cb6159d3f13"
print(string.partition("://"))
print(string.rpartition("://"))

13、join链接字符串

strings = ["hello", "world", "ha"]
strTemp = "*"
strTemp = strTemp.join(strings)
print(strTemp)

以上代码可以在GitHub找到。

上一篇 下一篇

猜你喜欢

热点阅读