字符串是 Python 中最常用的数据类型。

字符串是以单引号或双引号括起来的任意文本,可以使用""或''来创建字符串。例如:name = "Tom"

注:字符串一旦创建就不可修改,若修改或拼接则会在内存空间中生成新的字符串

连接字符串

str2 = "who is"
str3 = " mid ?"
str4 = str2 + str3
print(str4)

结果:

who is mid ?

 

输出相同字符串

str5 = "good" *4

print(str5)

结果:

goodgoodgoodgood

 

通过索引、下标来获取字符串中的某个字符

str6 = "he is a boy!"

print(str6[0:2])

结果:

he

 

格式化输出

格式化字符串时,Python使用一个字符串作为模板。模板中有格式符,这些格式符为真实值预留位置,并说明真实数值应该呈现的格式。

%d    %s   %f   占位符(格式符)

str9 = "sun is a nice man!"
num = 11
f = 10.87867544
                                # ↓ 精确小数点后三位,四舍五入
print("num = %d, str9 = %s, f = %.3f" % (num, str9, f))

结果:

num = 11, str9 = sun is a nice man!, f = 10.879

 

转义字符

转义字符  可以转义很多字符,比如 表示换行,表示制表符,字符  本身也要转义,所以表示的字符就是 

str9 = "sun is a nice man!"
num = 11
f = 10.87867544

print("num = %dnstr9 = %snf = %.3f" % (num, str9, f))

结果:

num = 11

str9 = sun is a nice man!

f = 10.879

 

Python3允许用“...”的格式表示多行内容

print('''
good
nice
very
''')

结果:

good

nice

very

 

如果字符串内有许多字符串都需要转义,为了简化 python 允许用 r 表示内部的字符串默认不转义。

print("C:\Program Files (x86)\NVIDIA Corporation")

print(r"C:Program Files (x86)NVIDIA Corporation")

结果:

C:Program Files (x86)NVIDIA Corporation

C:Program Files (x86)NVIDIA Corporation

 

内容来源于网络如有侵权请私信删除
你还没有登录,请先登录注册
  • 还没有人评论,欢迎说说您的想法!