startwith
方法是用来测试字符串是否以给定字符串开始。
in
操作符用来检验一个给定字符串是否为另一个字符串的一部分。
find
方法用来找出给定字符串在另一个字符串中的位置,或者返回-1以表示找不到子字符串。
str
类也有以一个作为分隔符的字符串join
序列的项目的整洁的方法,它返回一个生成的大字符串。
#!/usr/bin/python # Filename: str_methods.py name = 'Swaroop' # This is a string object if name.startswith('Swa'): print 'Yes, the string starts with "Swa"' if 'a' in name: print 'Yes, it contains the string "a"' if name.find('war') != -1: print 'Yes, it contains the string "war"' delimiter = '_*_' mylist = ['Brazil', 'Russia', 'India', 'China'] print delimiter.join(mylist)
$ python str_methods.py Yes, the string starts with "Swa" Yes, it contains the string "a" Yes, it contains the string "war" Brazil_*_Russia_*_India_*_China