第六章 字符串

2019-03-20  本文已影响0人  你笑的那么美丶

创建

s1 = 'shark'
s2 = "shark"
s3 = """hello shark"""
s4 = '''hello shark'''
s5 = """hello
shark
"""

简单操作

\ 转义符

testimony = 'This shirt doesn\'t fit me'

words = 'hello \nworld'

+拼接

print('hello' + 'world')

不可以用 字符串和 一个非字符串类型的对象相加

'number' + 0   # 这是错误的

* 复制

print('*' * 20)
print('shark' * 20)

字符串 和 0 或者 负数相乘,会得到一个空字符串

In [76]: 'hey' * 0
Out[76]: ''

In [77]: 'hey' * -3
Out[77]: ''

进阶操作

认识 Python 中第一个数据结构 序列类型

字符串型就是 python 序列类型的数据结构中的一种,本质是

字符序列

序列类型的特点

s1 = "shark"

image
获取元素
# 获取单个元素
s1[0]
s1[3]
s1[-1]

切片

image
# 使用切片获取多个元素
s1[0:2]

下面这样的操作,是的不到我的

s1[-1:-3]

# 获取字符串的长度,包含空格和换行符
len(s1)

利用字符串对象的方法

split

url = 'www.qfedu.com 千锋官网'
url.split()

li = url.split('.')

host, *_ = url.split('.', 1)

rsplit 从右向左分割

url = 'www.qfedu.com'
url2 = url.rsplit('.', 1)

replace 替换

url = 'www.qfedu.com'
url2 = url.replace('.', '_')

strip 移除两端的空格

s = ' hello   '
s2 = s.strip()

inp = input(">:").strip()

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 image image

交互输入

image
上一篇下一篇

猜你喜欢

热点阅读