一、字符串的定义
字符串 就是一系列字符。在 Python 中,用引号括起的都是字符串,其中的引号可以是单引号,下面的c在使用单引号的时候,需要转译,这是由于句子中含有单引号,也可以是双引号,如下所示:
- b = 'hello'
- c = 'what\'s up'
- a = "what's up "
- print(a)
- print(b)
- print(c)
二、字符串的特性
总共有以下集中特性:
1、索引
- s = 'hello'
- print(s[0])
- print(s[1])
-
- 打印结果:打印出s中索引值为0和索引为1的
- h
- e
2、切片
- s = 'hello'
- 切片的规则:s[start:end:step] 从start开始到end-1结束,步长:step
- print(s[0:3]) 打印前三个
- print(s[0:4:2]) 每隔两个步长取索引对应的元素
2.1显示所有字符
- s ='hello'
- print(s[:])
-
- 打印结果:
- hello
-
- 显示前3个字符
- print(s[:3])
- hel
-
- 对字符串倒叙输出
- print(s[::-1])
- olleh
-
- 除了第一个字符以外,其他全部显示
- print(s[1:])
- ello
3、重复
- print(s*5)
-
- 打印结果:
- hellohellohellohellohello
4、连接
用+号连接
- print(s + 'world')
- print(s + " " 'world') 以空格连接
-
- 打印结果:
- helloworld
- hello world
5、成员操作符
- print('h' in s )
-
- 打印:
- True
6、for 循环(迭代)
- for i in s:
- print(i)
-
- 打印结果:
- h
- e
- l
- l
- o
三、练习
判断所输入的数字是否为回文数:
- num = input('Num:')
- if num == num[::-1]:
- print('这是一个回文数')
- else:
- print('这不是一个回文数')
-
- 打印结果:
- Num:121
- 这是一个回文数