
字符串、整数、浮点
字符串用单引号''或者双引号"",或者三引号"""包围
python 代码解读复制代码# 单引号
>>> print('hello')
hello
# 双引号
>>> print("hi")
hi
# 输出转义
# \n换行符; \t制表符
>>> print("First Line. \nSecod Line")
First Line
Second Line
# 原始输出,不进行转义,在字符串前添加r
>>> print(r"First Line. \nSecond Line")
First Line. \nSecond Line
# 保留字符串中的换行格式,使用三重单引号或者双引号
>>> print("""
hello
world
""")
(输出时这里还会有一个空行)
hello
world
)
# 三重引号后添加\,可以将第一行的空行删除
>>>print("""\
hello
world
""")
(输出时这里没有空行)
hello
world'*'重复输出
python 代码解读复制代码# * 重复输出字符串
>>> print(3 * hi + world)
hihihiworld+ 字符串拼接
python 代码解读复制代码# + 字符串拼接
>>> print('Py' 'thon')
Python字符串索引
python 代码解读复制代码# 字符串支持索引访问
>>> word = 'python'
>>> print(word[0])
p
# 0 和-0为同一索引位置
>>> print(word[-0])
p
>>>print(word[1])
y
# 负索引
# 由于0 和-0为同一个位置所以,字符串所在右边字符的第一个字符的下标为[-1]
>>> print(word[-1])
n
# 索引下标越界
# python的长度为6,正索引最大为5,负索引最小为-6,数值超过范围则会出错
>>> print(word[8])
Index Error :string index out of range字符串区间索引-字符串截取
python 代码解读复制代码>>> word = "python"
# 区间索引左侧闭区间,右侧为开区间
>>> print(word[0:2])
py
# 索引省略
# 省略开头索引
# 省略后默认从0开始
>>> print(word[:2])
py
# 省略结尾索引
>>> print(word[2:])
thon
# 区间索引值超过索引范围,不会报错,只是不返回值
>>> print(word[42:])
>>> print(word[9:])字符串为immutable,不可被重新编辑
python 代码解读复制代码>>> word = "python"
>>> word[1] = 'j'
TypeError:'str' object does not support item assignment
# 要生成不同的字符串,应新建一个字符串
>>> word2 = j + word[:2]python 代码解读复制代码str = 'hellopython'
print(str.islower())
Truepython 代码解读复制代码str = 'hellopython'
print(str.isspace())
Falsepython 代码解读复制代码str = 'hellopython'
print(str.issupper())
Fasepython 代码解读复制代码str = 'HelloPython'
print(str)
hellopythonpython 代码解读复制代码str = 'HelloPython'
print(str.upper())
HELLOPYTHONpython 代码解读复制代码str = 'hellopython'
print(len(str))
11如果指定的前缀不存在,得到的则是原始字符
python 代码解读复制代码str = 'hellopython'
print(str.removeprefix('on'))
htllopyth如果指定后缀不存在,则返回原字符串
python 代码解读复制代码str = 'hellopython'
print(str.removesuffix('he'))
llopythonpython 代码解读复制代码str = 'hellopython'
print(str.count('ll', 0, 12))
1python 代码解读复制代码str = 'hellopython'
print(str.endwith('B'))
False本文系转载,前往查看
如有侵权,请联系 cloudcommunity@tencent.com 删除。
本文系转载,前往查看
如有侵权,请联系 cloudcommunity@tencent.com 删除。