>>> print('he said "good", you said "great", and i want to say """excellent"""')
he said "good", you said "great", and i want to say """excellent""" 二 string的join和split函数
#string find
searchStr = "Red Blue Violet Green Blue Yellow Black"
print (searchStr.find("Red"))
print (searchStr.rfind("Blue"))
print (searchStr.index("Blue"))
print (searchStr.index("Blue",20))
print (searchStr.rindex("Blue"))
print (searchStr.rindex("Blue",1,18))
f='file.py'
if f.endswith('.py'):
print ("Python file: " + f)
elif f.endswith('.txt'):
print ("Text file: " + f)
#string replace
question = "What is the air speed velocity of an unlaiden swallow?"
question2 = question.replace("swallow", "European swallow")
print(question2)
对于子字符串的查找,可以使用in,可读性更好。
if 'hello world,hello'.find('world') != -1 : print('find')
if 'world' in 'hello world,hello' : print('find')
四 print函数中str的格式
#string rjust and ljust
chapters = {1:5, 2:46, 3:52, 4:87, 5:90}
for x in chapters:
print ("Chapter " + str(x) + str(chapters[x]).rjust(15,'.'))
#Chapter 1..............5
#Chapter 2.............46
#Chapter 3.............52
#Chapter 4.............87
#Chapter 5.............90
#print
name='buddy'
print("welcome" + " " + name + ", you are very handsome!" )
print("welcome", name, ", you are very handsome!" )
print('welcome %s, you are very handsome!' %name)
#welcome buddy, you are very handsome!
#welcome buddy , you are very handsome!
#welcome buddy, you are very handsome!
#print string format
chapters2 = {1:5, 2:46, 3:52, 4:87, 5:90}
for x in chapters2:
print ("Chapter %d %15s" % (x,str(chapters2[x])))
#Chapter 1 5
#Chapter 2 46
#Chapter 3 52
#Chapter 4 87
#Chapter 5 90 print函数中使用%来隔离格式str和变量。