06-字符串基础
2020-03-31 本文已影响0人
shan317
前面我们已经提过,python对单双引号无区别,但单引号或双引号可以相互转义
sentence = 'tom\'s pet is a cat' # 单引号中间还有单引号,可以转义
sentence2 = "tom's pet is a cat" # 也可以用双引号包含单引号
sentence3 = "tom said:\"hello world!\""
sentence4 = 'tom said:"hello world"'
# 三个连续的单引号或双引号,允许输入多行字符串,并且保留输入格式
words = """
hello
world
abcd"""
print(words)
py_str = 'python'
# 获取字符串长度
print(len(py_str)) # 6
# 获取字符串第一个字符
print(py_str[0]) # p
# 获取字符串最后一个字符
print(py_str[-1]) # n
# 错误,提示下标越界
# print(py_str[6]) # IndexError: string index out of range
# 切片,起始下标包含,结束下标不包含
print(py_str[2:4]) # th
# 从下标为2的字符取到结尾
print(py_str[2:]) # thon
# 从开头取到下标是2之前的字符
print(py_str[:2]) # py
# 获取全部
print(py_str[:]) # python
# 步长值为2,默认是1
print(py_str[::2]) # pto
# 取出yhn
print(py_str[1::2]) # yhn
# 步长为负,表示自右向左取
print(py_str[::-1]) # nohtyp
# 简单的拼接到一起
print(py_str + ' is good') # python is good
# 把字符串重复3遍
print(py_str * 3) # pythonpythonpython
print('t' in py_str) # True
print('th' in py_str) # True
print('to' in py_str) # False
print('to' not in py_str) # True