字符串

2019-09-25  本文已影响0人  光明_7c13

创建

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

简单操作

\转义符

testimony = 'This shirt doesn\'t fit me'
words = 'hello \nworld'

+拼接

print('hello' + 'world')

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

'number' + 0   # 这是错误的

* 复制

print('*' * 20)
print('apple' * 20)

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

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

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

获取元素

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

切片

[start:end:step]
start 永远是起始索引号
end  永远是终止索引号
step  是可选的步长

切片操作只包位于起始索引号位置的元素,
不包含位于终止索引号位置的元素;
同时,起始和终止的意义都是针对于从左向右的顺序来定义的
# 使用切片获取多个元素
s1[0:2]

利用字符串对象的方法
split 按符号分割

url = 'aaa.sss.ccc'
li = url.split('.')
a,li=url.split('.',1)
找到第一个`.`分割

rsplit 从右向左分割

url = 'aaa.sss.ccc'
li = url.rsplit('.')

replace 替换

url =  'aaa.sss.ccc'
url = url.replace('.', '_')

strip 移除两端的空格

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

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

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')

obj.capitalize() #字符串的首字母变大写,其他的字母都变小写
obj.title() #单词首字母大写
obj.upper() #全部变大写
boj.lower() #全部变小写

上一篇 下一篇

猜你喜欢

热点阅读