10个有用的Python字符串函数小结( 二 )


count() 函数查找指定值(由用户给定)在给定字符串中出现的次数 。
语法: string .count( value, start, end )
示例 1:返回值“CSDN ”在字符串中出现的次数
string = "CSDN is the largest developer community in China" print(string.count("CSDN "))

输出:
1
示例 2: 返回值“CSDN ”在字符串中 从位置 8 到 16 出现的次数
string = "CSDN is the largest developer community in China" print(string.count("analytics", 8, 16))
输出:
0

七、find( ) 函数
find() 函数查找指定值的第一次出现 。如果在该字符串中找不到该值,则返回 -1 。
find() 函数与 index() 函数几乎相同,但唯一的区别是 index() 函数在找不到值时引发异常 。
语法:string.find(value, start, end)
示例 1:文本中字母“d”第一次出现的位置是什么?
string = "CSDN is the largest developer community in China" print(string.find("d"))
输出:
20
示例 2:仅在位置 5 和 16 之间搜索时,字母“d”在文本中的哪个位置首次出现?
string = "CSDN is the largest developer community in China" print(string.find("d", 12, 22))
输出:
20
示例 3:如果找不到该值,则 find() 函数返回 -1,但 index() 函数会引发异常
string = "CSDN is the largest developer community in China" print(string.find("d", 5, 10))
输出:
-1

八、replace() 函数
replace() 函数用另一个指定的短语替换指定的短语 。
注意:如果没有指定任何其他内容,所有出现的指定短语都将被替换 。
语法: string .replace( oldvalue, newvalue, count )
示例 1:替换所有出现的单词“developer ”
string = "CSDN is the largest developer community in China" print(string.replace("largest ", "best "))
输出:
CSDN is the best developer community in China
示例 2:仅替换第一次出现的单词“developer ”
string = "CSDN is China's largest developer community suitabsle for developer to learn" print(string.replace("developer ", "developers ", 1))
输出:
CSDN is China's largest developers community suitabsle for developer to learn

九、swapcase( ) 函数
swapcase() 函数返回一个字符串,其中所有大写字母都是小写字母,反之亦然 。
语法:string.swapcase()
示例 1:将小写字母变为大写,将大写字母变为小写
string = "CSDN is the largest developer community in China" print(string.swapcase())
输出:
csdn IS THE LARGEST DEVELOPER COMMUNITY IN cHINA
示例 2:如果有数字而不是字符会发生什么
string = '3th CSDN force plan activities are very good' print(string.swapcase())
输出:
3TH csdn FORCE PLAN ACTIVITIES ARE VERY GOOD

十、join () 函数
join() 函数获取可迭代对象中的所有项并将它们连接成一个字符串 。我们必须指定一个字符串作为分隔符 。
语法:string.join(iterable)
示例 1:将给定元组中的所有项连接成一个字符串,使用 #(hashtag)字符作为分隔符
myTuple = ("Computer Scientist", "Programming Learning", "Python Programming") x = " # ".join(myTuple) print(x)
输出:
Computer Scientist # Programming Learning # Python Programming
示例2:将给定字典中的所有项目连接成一个字符串,使用单词“TEST”作为分隔符
myDict = {"name": "CSDN", "country": "China", "Technology": "Python Programming"} mySeparator = "TEST" x = mySeparator.join(myDict) print(x)
输出:
nameTESTcountryTESTTechnology
到此这篇关于10个有用的Python字符串函数小结的文章就介绍到这了,更多相关Python字符串函数内容请搜索趣讯吧以前的文章或继续浏览下面的相关文章希望大家以后多多支持趣讯吧!

推荐阅读