python 字符串和转义字符

python 字符串和转义字符

1、字符串

字符串是一种表示文本的数据类型,字符串可以使ASCII字符、各种符号以及各种Unicode字符,在python中,共有三种字符串的表现形式:

  • 使用单引号包含字符串
  • 使用双引号包含字符串
  • 使用三引号包含字符串

虽然三种方式的最终含义是一致的,但是当字符串中包含时不可以使用单引号;同理当字符串中包含“”时不可以使用双引号。

# 单引号
a = 'pytonn'
print(a)

# 双引号
b = "python"
print(b)

# 三引号
c = """python"""
print(c)

# 不可以使用单引号
d = "I'm Neal"
print(d)

# 不可以使用双引号
e = '"nice to meet you", he said'
print(e)

2、转义字符

如果非要在字符串包含的条件下使用单引号括起来,则此时需要使用转义字符\。此时python就会知道反斜线后后面的单引号并不是结束的标记。

# 转义字符 \
f = 'I\'m Meal'
print(f)

python中像这样的转义字符还有很多,见下表:

python 字符串和转义字符_第1张图片

当不想让\表示转义字符时,可以在其前面加r,其代表原始的字符串。

g = "hello \t python"
print(g) # hello 	 python

h = r"hello \t python"
print(h) # hello \t python

你可能感兴趣的:(python,#,基础知识,python,字符串,转义字符)