2022年 11月 4日

python中字符串定义及特性

一、字符串的定义

  字符串 就是一系列字符。在 Python 中,用引号括起的都是字符串,其中的引号可以是单引号,下面的c在使用单引号的时候,需要转译,这是由于句子中含有单引号,也可以是双引号,如下所示:

  1. b = 'hello'
  2. c = 'what\'s up'
  3. a = "what's up "
  4. print(a)
  5. print(b)
  6. print(c)

二、字符串的特性

总共有以下集中特性:

1、索引

  1. s = 'hello'
  2. print(s[0])
  3. print(s[1])
  4. 打印结果:打印出s中索引值为0和索引为1
  5. h
  6. e

2、切片

  1. s = 'hello'
  2. 切片的规则:s[start:end:step] 从start开始到end-1结束,步长:step
  3. print(s[0:3]) 打印前三个
  4. print(s[0:4:2]) 每隔两个步长取索引对应的元素

2.1显示所有字符

  1. s ='hello'
  2. print(s[:])
  3. 打印结果:
  4. hello
  5. 显示前3个字符
  6. print(s[:3])
  7. hel
  8. 对字符串倒叙输出
  9. print(s[::-1])
  10. olleh
  11. 除了第一个字符以外,其他全部显示
  12. print(s[1:])
  13. ello

3、重复

  1. print(s*5)
  2. 打印结果:
  3. hellohellohellohellohello

4、连接

用+号连接

  1. print(s + 'world')
  2. print(s + " " 'world') 以空格连接
  3. 打印结果:
  4. helloworld
  5. hello world

5、成员操作符

  1. print('h' in s )
  2. 打印:
  3. True

6、for 循环(迭代)

  1. for i in s:
  2. print(i)
  3. 打印结果:
  4. h
  5. e
  6. l
  7. l
  8. o

三、练习

判断所输入的数字是否为回文数:

  1. num = input('Num:')
  2. if num == num[::-1]:
  3. print('这是一个回文数')
  4. else:
  5. print('这不是一个回文数')
  6. 打印结果:
  7. Num:121
  8. 这是一个回文数