Python(四):字符串

概念

字符串是 可迭代不可变 对象
如,s[0]='e' 改变一个字符串内部的字符报错

字符串的定义:单引号、双引号、三引号

操作

基本序列操作

索引(正负)、切片、遍历元素、查找(in)

s = ' abc def '

# 索引(正负)
print(s[1], s[-2])
# 切片
print(s[1:3])
print(s[:])
# 遍历元素
for i in s:
	print(i)
# 查找:in
print('bc ' in s)		# True

拼接(+)、相乘

s = ' abc def '

# 相加:拼接
print('abc'+'d')
# 相乘:重复
print('abc'*3)

排序、反转、比较、复制

Python(二十五):排序、反转

Python(十九):比较、深浅拷贝


字符串的方法

查找(find、index)

str.find(sub)
'''
子字符串 sub 在 str 中的第一次位置。
返回:最小下标,没找到为-1
'''

s = ' abc def '
print(s.find(' '))		# 0
print(s.find('g'))		# -1
str.index(sub)
'''
子字符串 sub 在 str 中的第一次位置。
返回:最小下标,没找到报错
'''

s = ' abc def '
print(s.index(' '))		# 0
print(s.index('g'))		# 报错

拼接(join)

str.join(iterable)
'''
相当于用 str 做 iterable 的分隔符。
iterable:元素必须是【字符串】
返回:字符串
'''

s = '-'
li = ['1', '2', '3']
print(s.join(li))		# '1-2-3'

s2 = '123'
print(s.join(s2))		# '1-2-3'

s3 = ['1']
print(s.join(s3))		# '1'

s4 = []
print(s.join(s4))		# ''

分割(split)

str.split(sep=None, maxsplit=-1)
'''
以 sep 作为分隔符分割字符串,最多进行 maxsplit 次拆分。
sep=None,	其结果将不包含开头或末尾的【空白】符,连续的【空白】会被视为单个分隔符
maxsplit=-1,最多次分隔
返回:列表
'''

print('abcdef'.split())						# ['abcdef']
print('\tabc\t\t   def\t'.split())			# ['abc', 'def']
print(' abc def '.split(' '))				# ['', 'abc', 'def', '']

替换(replace)

print('abcdef'.replace('bc', ''))		# adef
print('abcdef'.replace('bc', 'BC'))		# aBCdef

移除首末字符(strip、lstrip、rstrip)

str.strip(sep)
'''
sep=None,移除首末所有连续【空白】
'''

print(' \t abc def\n '.strip())		# ‘abc def’
print(' \t abc def\n '.lstrip())	# ‘abc def\n ’
print(' \t abc def\n '.rstrip())	# ‘ \t abc def’

判断(isxxx)

# 全是数字:isdigit
print('1234'.isdigit())			# True
# 全是字母:isalpha
print('abc'.isalpha())			# True
# 全是数字或字母:isalnum
print('1234.def'.isalnum())		# False	有点

# 全是小写
print('abc'.islower())		# True
# 全是大写
print('ABC'.isupper())		# True
# 标题字符串:首大写
print('A'.istitle())		# True
print('Abc'.istitle())		# True

大写、小写、标题(supper()、lower()、title())

print('abcDEF'.supper())
print('abcDEF'.lower())
print('abcDEF'.title())

格式化(format、f)

str.format()、f’’

# 字符串中含有{}的替换值

print('1 + 2 = {} {}'.format(3, 'is right.'))	
print('1 + 2 = {0} {1}'.format(3, 'is right.'))		# 1 + 2 = 3 is right.
print('{0} is list.'.format([1,2,3]))				# [1, 2, 3] is list.			注意list中的空格
print('{0} is dict.'.format(('a':1,'b':2))			# {'a': 1, 'b': 2} is dict.			注意dict中的空格


s1 = 3
s2 = 'is right.'
print(f'1 + 2 = {s1} {s2}')							# 1 + 2 = 3 is right.

%

print('%s, %d, %.2f'%('abc', 100, 2.4567))

查找:出现次数(count)

str.count(sub)
'''
子字符串 sub 在 str 中出现的次数(不重叠)
'''

s = 'bbbbbbb'
sub = 'bb'
print(s.count(sub))		# 3

进阶

+=:拼接更高效

str1 += str2
str1 = str1 + str2
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值