类数组
>>> hello = "Hello, World"
>>> print(hello[1])
e
>>> print(hello[-1])
d
获取位置 1
或最后的字符
循环
>>> for char in "foo":
... print(char)
f
o
o
遍历单词 foo
中的字母
切片字符串
┌───┬───┬───┬───┬───┬───┬───┐
| m | y | b | a | c | o | n |
└───┴───┴───┴───┴───┴───┴───┘
0 1 2 3 4 5 6 7
-7 -6 -5 -4 -3 -2 -1
>>> s = 'mybacon'
>>> s[2:5]
'bac'
>>> s[0:2]
'my'
>>> s = 'mybacon'
>>> s[:2]
'my'
>>> s[2:]
'bacon'
>>> s[:2] + s[2:]
'mybacon'
>>> s[:]
'mybacon'
>>> s = 'mybacon'
>>> s[-5:-1]
'baco'
>>> s[2:6]
'baco'
步长
>>> s = '12345' * 5
>>> s
'1234512345123451234512345'
>>> s[::5]
'11111'
>>> s[4::5]
'55555'
>>> s[::-5]
'55555'
>>> s[::-1]
'5432154321543215432154321'
字符串长度
>>> hello = "Hello, World!"
>>> print(len(hello))
13
len()
函数返回字符串的长度
多份
>>> s = '=+'
>>> n = 8>>> s *'=+=+=+=+=+=+=+===+'
检查字符串
>>>s = 'spam'
>>> s in 'I saw spamalot!'
True
>>> s not in 'I saw The Holy Grail!'True
连接
>>> s = 'spam'
>>> t = 'egg'
>>> s +'spamegg'
>>> 'spam' 'egg''spamegg'
格式化
name = "John"
print("Hello, %s!" % name)
name = "John"
age = 23
print("%s is %d years old." % (name, age))
format() 方法
txt1 = "My name is {fname}, I'm {age}".format(fname="John", age=36)
txt2 = "My name is {0}, I'm {1}".format("John", 36)
txt3 = "My name is {}, I'm {}".format("John", 36)
Input 输入
>>> name = input("Enter your name: ")
Enter your name: Tom
>>> name
'Tom'
从控制台获取输入数据
Join 加入
>>> "#".join(["John", "Peter", "Vicky"])'John#Peter#Vicky'
Endswith 以..结束
"Hello, world!".endswith("!")True
转义符号
| 输出反斜杠 |
| 输出单引号 |
| 输出双引号 |
| 换行 |
| 水平制表符 |
| 光标回到首位 |
| 退格 |