07讲 字符串数据类型的介绍和字符串数据索引和切片及format的基本应用

字符串类型及格式化
字符串类型
>>> type("2")
      #字符串类型,加 “ ”
>>> a="abc"
>>> type(a)

运行错误(就近组合,无效字符)

>>> a="She said"Hello World""
SyntaxError: invalid syntax

边界符:单引号

>>> a="She said'Hello World'"
>>> a
"She said'Hello World'"

三引号
三引号换行运行

>>> a="""Hello
World"""
>>> a
'Hello\nWorld'      #\n表示换行,回车

>>> a="Hello      
SyntaxError: EOL while scanning string literal

Python语言转义符:
eg:\n 表示换行,\ 表示反斜杠,' 表示单引号,\t 表示制表符(TAB等)

>>> "\'"
"'"
>>> "'"
"'"
>>> '\''
"'"
>>> '''

字符串索引
>>> a="World"
>>> a[3]
'l'
>>> a[-2]
'l'
>>> a[-3]
'r'

>>> "World"[3]
'l'
字符串切片
>>> a="World"
>>> a[1:3]
'or'
>>> a[3:]
'ld'
>>> a[:2]
'Wo'
>>> a[-1:-3]
''
>>> a[-3:-1]
'rl'

单向计数

>>> a="World"
>>> a[1,-3]
Traceback (most recent call last):
  File "", line 1, in 
    a[1,-3]
TypeError: string indices must be integers
format() 方法的基本使用
>>> a="Mstmxly"
>>> "I am {}".format(a)
'I am Mstmxly'
>>> b="Shirley"
>>> "I am {} or {}".format(a,b)
'I am Mstmxly or Shirley'
>>> "I am {1} or {0}".format(a,b)
'I am Shirley or Mstmxly'

>>> a="Shirley"
>>> b="student"
>>> "{} is a {}".format(a,b)
'Shirley is a student'

>>> "{0} is a {1}".format(a,b)
'Shirley is a student'
>>> "{1} is a {0}".format(a,b)
'student is a Shirley'

你可能感兴趣的:(07讲 字符串数据类型的介绍和字符串数据索引和切片及format的基本应用)