blog/docs/code/python/string.md

1.8 KiB
Raw Permalink Blame History

title date tags categories author
String字符串 2020-07-21 22:09:54
Python
Python
Anges黎梦

字符串的定义

字符串是 Python 中最常用的数据类型。我们可以使用引号('或")来创建字符串。

定义单行字符串

var1 = 'hello world'
var2 = "hello world"
print(var1, var2)

执行结果:

hello world hello world

多行字符串

var3 = """
放大看风景的路上风景看
电视了风急浪大
撒克己复礼的撒附近的咳
嗽了几分六日哦额温暖mcvoe"""
print(var3)

执行结果:

放大看风景的路上风景看
电视了风急浪大
撒克己复礼的撒附近的咳
嗽了几分六日哦额温暖mcvoe

字符串取值

Python 不支持单字符类型,单字符在 Python 中也是作为一个字符串使用。

index取值方式

取字符串中的内容是从0开始计数

var4 = 'helloworld'
print(var4[0])  # 第一个字符
print(var4[-1]) # 最后一个字符
print(var4[2:6])    # 取第三个开始,至第六个结束的内容,等于:小于
print(var4[1:-1])   # 取从第二个开始,至倒数第一个字符结束的内容

执行结果:

h
d
llow
elloworl

字符串拼接

a = '111'
b = '222'
print(a+b)
print(a[0] + "23")

执行结果:

111222
123

更新其中某一段字符

错误示例:

# a[1] = 2    TypeError: 'str' object does not support item assignment
# print(a[0]+2+a[-1]) # TypeError: can only concatenate str (not "int") to str

基础类型操作,只允许同类型进行操作,比如 +

print(a[0]+"2"+a[-1])

执行结果:

121

重复输出

print(a*3)

执行结果:

111111111

字符判断

包含和不包含关系判断

print("1" not in a)
print("2" not in a)

执行结果:

False
True