创建
s1 = 'lenovo'
s2 = "QF"
s3 = """hello lenovo"""
s4 = '''hello 千锋云计算'''
s5 = """hello
shark
"""
s6 = '''hello
world'''
简单操作
\
转义符
testimony = 'This shirt doesn\'t fit me'
words = 'hello \nshark'
+
拼接
print('hello' + 'lenovo')
不可以用 字符串和 一个非字符串类型的对象相加
'lenovo' + 1 # 这会报错的
*
复制
print('*' * 20)
print('lenovo 666' * 20)
字符串 和 0 或者 负数相乘,会得到一个空字符串
>>> "hey" * 0
''
>>> "hey" * -100
''
>>>
进阶操作
字符串 是 Python 中的一个 序列类型 的数据结构
-
存放的数据,在其内是有序的,内部的数据是可以通过在其
内部所处的位置进行访问等操作。
序列类型的特点
序列里的每个数据被称为序列的一个元素
-
元素在序列里都是有个自己的位置的,这个位置被称为索引或
者叫偏移量,也有叫下标的
下标索号好从
0
开始的序列中的每一个元素可以通过这个元素的索引号来获取到
获取序列类型数据中的多个元素需要用切片的操作来获取到
s1 = "shark"
image.png
获取元素
# 获取单个元素
s1[0]
s1[3]
s1[-1]
切片
image.png
# 使用切片获取多个元素
s1[0:2]
下面这样的操作,臣妾做不到
s1[-1:-3]
因为从左向右开始操作, 索引号
-1
的右边没有任何索引号了
-3
在-1
的左边
# 获取字符串的长度,包含空格和换行符
n = len(s1)
print(n)
利用字符串对象的方法
- split 分割
默认使用 空格或者 Tab 间做为分隔符
>>> url = 'www.qfedu.com 千锋官网'
>>> url.split()
['www.qfedu.com', '千锋官网']
可以指定分隔符
>>> ip = '192.168.1.100'
>>> ip.split('.')
['192', '168', '1', '100']
rsplit 从右向左分割
找到第一个分隔符,就结束。
>>> ip.rsplit('.', 1)
['192.168.1', '100']
>>>
replace 替换
url = 'www.qfedu.com'
url2 = url.replace('.', '_')
strip 移除字符串两端的空白字符
>>> s = ' shark '
>>> s
' shark '
>>> s.strip()
'shark'
>>>
s = "symbol=BCHBTC;baseCoin=BCH;quoteCoin=BTC;"
s_list = s.split(';')
# print(s_list)
# ['symbol=BCHBTC', 'baseCoin=BCH', 'quoteCoin=BTC', '']
startswith 判断字符串以什么为开头
s = 'hello world'
if s.startswith('h'):
print(s)
endswith 判断字符串以什么为结尾
s = 'hello world'
if s.endswith('d'):
print(s)
index 获取一个元素在字符串中的索引号
s = 'hello world'
idx = s.index('l')
千锋教育云计算
交互输入
image.png
对于字符串和字节串类型来说,当且仅当 x 是 y 的子串时
x in y
为True
。
空字符串总是被视为任何其他字符串的子串,因此"" in "abc"
将返回True
。