python之字符串的简单操作:连接,重复,索引,切片,长度,遍历
字符串的简单操作
连接,重复,索引,切片,长度,遍历
连接
<str> + <str>
例子1
a = 'I'
b = 'love'
c = 'you'
print(a + b + c)
# Iloveyou
例子2
a = 'I'
b = 'love'
c = 'you'
print(a + ' ' + b + ' ' + c)
# I love you
错误例子
a = 2
b = '3'
c = a + b
# TypeError: unsupported operand type(s) for +: 'int' and 'str'
# int型 和 str型不能连接
重复
<str>*<int>
例子1
a = '2'
b = '3'
print(a + b*3)
# 2333
例子2
a = '2'
b = '3'
c = 3
print(a + b*c)
# 2333
例子3
a = [2, 3]
print(a *3)
# [2, 3, 2, 3, 2, 3]
错误例子
a = '2'
b = '3'
print(a + b*3.0)
# ypeError: can't multiply sequence by non-int of type 'float'
#<int> 不能改为<float>
索引
<str>[index]
,返回一个字符
正索引的索引值从左到右,从0开始
负索引的索引值从右到左,从-1开始
例子1
a = 'abcdefg'
print(a[0])
# a
例子2
a = 'abcdefg'
print(a[2])
# c
例子3
a = 'abcdefg'
print(a[-1])
# g
例子4
a = 'abcdefg'
print(a[-5])
# c
错误例子
a = 'abcdefg'
print(a[100]) #print(a[-100])
# IndexError: string index out of range
# 索引值越界报错
切片
<str>[<int1>:<int2>]
,返回从<int1>
到<int2>
的字符串
<int1>
和<int2>
可以为空,为空时,<int1>
默认值为0,<int2>
默认值为n+1(n表示字符串最后一个字符的索引值)
例子1
a = 'abcdefg'
print(a[0:3])
# abc
例子2,<int1>
为空
a = 'abcdefg'
print(a[:3])
# abc
例子3<int2>
为空
a = 'abcdefg'
print(a[1:])
# bcdefg
例子4,<int1>
和<int1>
都为空
a = 'abcdefg'
print(a[:])
# abcdefg
例子5,当<int1>
大于<int2>
时<str>[<int1>:<int2>]
返回空值
a = 'abcdefg'
print(1)
print(a[3:2])
print(2)
# 1
#
# 2
例子6,利用切片去掉字符串末尾的换行符
# 不去掉换行符\n
a = 'abc\ndefg\n'
print(a[:])
#abc
#defg
#
# 去掉换行符\n
a = 'abc\ndefg\n'
print(a[:-1])
#abc
#defg
错误例子
a = 'abcdefg'
print(a[0:3.0])
# TypeError: slice indices must be integers or None or have an __index__ method
# <int1> 和 <int1>必须都为int型
遍历
例子
for i in '我爱你':
print(i)
# 我
# 爱
# 你
moyutime:本文仅是学习心得,观点仅供参考,祝愿读者学习途中快乐且不断有所收获。