字符串

  • 定义
>>> a = 'hello'
>>> b = 'what\'s up'
>>> c = "what's up"
>>> print(a)
hello
>>> print(b)
what's up
>>> print(c)
what's up
  • 索引
>>> s = 'hello'
>>> print(s[0])
h
>>> print(s[1])
e
  • 切片
>>> s = 'hello'
>>> print(s[0:3]) # 切片的规则:s[start:end:step] 从start开始到end-1结束,步长:step
hel
>>> print(s[0:4:2])
hl

#显示所有字符
>>> print(s[:])
hello

#显示前3个字符
>>> print(s[:3])
hel

#对字符串倒叙输出
>>> print(s[::-1])
olleh

#除了第一个字符以外,其他全部显示
>>> print(s[1:])
ello
  • 重复
>>> s = 'hello'
>>> print(s * 5)
hellohellohellohellohello
  • 连接
>>> s = 'hello'
>>> print(s + 'world')
helloworld
  • 成员操作符
>>> s = 'hello'
>>> print('h' in s)
True
>>> print('w' in s)
False
  • for循环(迭代)
>>> s = 'hello'
>>> for i in s:
...     print(i)
... 
h
e
l
l
o

Python 字符串

Python 字符串

Python 字符串

相关文章: