03Python - 字符串
序列的操作基本适用 但是不能改变, 只读数据段 和大多数语言一致。
>>> x = "YKDog"
>>> len(x)
5
>>> max(x)
'o'
>>> min(x)
>>> 'D'
>>> x[-3:] = "Man"
Traceback (most recent call last):
File "<pyshell#61>", line 1, in <module>
x[-3:] = "Man"
TypeError: 'str' object does not support item assignment
格式配对
>>> ft = "he is a %s"
>>> dog = "Dog"
>>> ft % dog
'he is a Dog'
>>> ft = "PI is %.3f"
>>> ft % pi
>>> from math import pi
>>> ft % pi
'PI is 3.142'
>>> '%s plus %s equals %s' % (2, 2, 4)
'2 plus 2 equals 4'
>>> '%.5s' % 'Guido van Rossum'
'Guido'
>>> '%.*s' % (5, 'God is a girl')
'God i'
价格表打印
width = 50
price_width = 10
item_width = width - price_width
h_ft = "%-*s%*s"
i_ft = "%-*s%*.2f"
print("=" * 50)
print (h_ft % (item_width , "Item", price_width, "Price"))
print("-" * 50)
print (i_ft % (item_width , "Apples", price_width, 0.4))
print (i_ft % (item_width , "Pears", price_width, 0.5))
print (i_ft % (item_width , "Dogs", price_width, 10))
print("-" * 50)
效果
==================================================
Item Price
--------------------------------------------------
Apples 0.40
Pears 0.50
Dogs 10.00
--------------------------------------------------
find函数查找字串位置, 找不到就返回-1
>>> "I am a pig".find("am")
2
>>> "I am a dog".find("pig")
-1
find字符串中有多个目标字符串的时候, 返回第一个位置。
>>> subject = "$$$ Get rich now$$$$"
>>> subject.find('$$$')
0
>>> subject = "A$$$$"
>>> subject.find("$$")
1
查找指定范围内的目标
>>> subject.find("l", 4, len(subject))
10
连接子字符串
>>> "*".join(("1", "2", "3"))
'1*2*3'
字符串的大小的转换
句子首个字母大写 OC中是每个单词首个字母大写
>>> "YKDog is a dog".lower()
'ykdog is a dog'
>>> "YKDog is a dog".upper()
'YKDOG IS A DOG'
>>> "YKDog is a dog".capitalize()
'Ykdog is a dog'
>>> "This is a dog".replace("is", "is not")
'This not is not a dog'
join可以连接元组和数组中的字符串
>>> x = "1+2+3+4".split("+")
>>> x
['1', '2', '3', '4']
>>> "*".join(x)
'1*2*3*4'
去掉字符串两侧指定的字符
>>> dogName = "******Wangcai*Dog**"
>>> dogName.strip("*")
'Wangcai*Dog'
网友评论