Python3基础之基本问题 问题1: 加法运算符重载 问题2:索引和分片重载 问题3,字符串问题

如果我们有两个列表对象,我要将两个列表中的元素依下标进行加和,我们该如何实现?

1列表对象的加法

list1 = [1,2,3,4]
list2 = [10,20,30,40]
list1 + list2
[1, 2, 3, 4, 10, 20, 30, 40]

2实现的第一种方法

list1_2 = []
for i,j in zip(list1,list2):
    list1_2.append(i+j)
print(list1_2)
[11, 22, 33, 44]

3实现的第二种方法

class add_list:
    def __init__(self, list_orignal):
        self.data = list_orignal[:] 
    def __add__(self, obj):
        x = len(self.data)
        y = len(obj.data)
        max_value = x if x<y else y
        xy = []
        for n in range(max_value):
            xy.append(self.data[n]+obj.data[n])
        return add_list(xy[:])
list1 = add_list([1,2,3,4,5])
list2 = add_list([10,20,30,40])
list1_2 = list1 + list2
print(list1_2.data)
[11, 22, 33, 44]

问题2:索引和分片重载

如果我们要自己创造一个对象,让这个对象具有列表、字符串等的相关功能,该如何实现?

class My_obj:
    # 初始化相关数据,使对象具有data属性,并赋值一个序列a
    def __init__(self,a):
        self.data = a[:]
    # 创建索引功能
    def __getitem__(self, index):
        return self.data[index]
    # 创建赋值功能
    def __setitem__(self,index,value):
        self.data[index]=value
    # 创建删除功能
    def __delitem__(self,index):
        del self.data[index]
x = My_obj([1,2,3,4,5,6])
x[:4]
[1, 2, 3, 4]
x[0] = 'a'
print(x.data)
['a', 2, 3, 4, 5, 6]
del x[0]
x.data
[2, 3, 4, 5, 6]

问题3,字符串问题

  • 字符串应用
    '1 2 3 4 5 6' ----> '6 5 4 3 2 1'
data = '1 2 3 4 5 6'
data_1 = data.strip().split(' ')
data_1.reverse()
print(' '.join(data_1))
6 5 4 3 2 1
  • 查看数据类型函数type()
print('True的数据类型:', type(True))
print('"abcd"数据类型:', type("abcd"))
print('1数据类型:', type(1))
print('1.1数据类型:', type(1.1))
print('(1,2,3)数据类型:', type((1,2,3)))
print('[1,2,3]数据类型:', type([1,2,3]))
print('{1,2,3}数据类型:', type({1,2,3}))
print('{1:a,2:b,3:c}数据类型:', type({1:'a',2:'b',3:'c'}))
True的数据类型: <class 'bool'>
"abcd"数据类型: <class 'str'>
1数据类型: <class 'int'>
1.1数据类型: <class 'float'>
(1,2,3)数据类型: <class 'tuple'>
[1,2,3]数据类型: <class 'list'>
{1,2,3}数据类型: <class 'set'>
{1:a,2:b,3:c}数据类型: <class 'dict'>
  • 'English','Chinese','Usa'等首字母大写,其余字母小写的单词

    capitalize

x = 'abcdefghigk'
x_1 = x.capitalize()
print(x_1)
Abcdefghigk
  • 字符串居中 center(长度,'默认为空白')
x = 'bright, how are you'
x_1 = x.center(40,'$')
print(x_1)
$$$$$$$$$$bright, how are you$$$$$$$$$$$
  • 全大写:upper 全小写:lower
x1 = 'bright'
x2 = 'BRIGHT'
x1_upper = x1.upper()
print('小写变大写',x1_upper)
x2_lower = x2.lower()
print('大写变小写',x2_lower)
小写变大写 BRIGHT
大写变小写 bright
  • startswith('检测字符'[,start,end])endswith('检测字符'[,start,end])
x = 'bright'
print(x.startswith('b')) # 是否以b开头
print(x.endswith('t'))   # 是否以t结尾
print(x.startswith('ri',1,3))
True
True
True
  • 字符串中,大写变小写,小写变大写 swapcase()
x = 'bRIGHT,tHE, hOW'
print(x.swapcase())
Bright,The, How
  • 字符串内词汇首字母大写title
x = 'hai, bright, how#are$you'
print(x.title())
Hai, Bright, How#Are$You
  • index:通过元素找索引,可切片,找不到,报错;find:通过元素找索引,可切片,找不到,返回-1
x = 'bright, how are you'
print('找字符h的下标',x.find('h'))
print('从第五个下标开始,找字符h的下标',x.find('h',6))
print(x.find('@'))
找字符h的下标 4
从第五个下标开始,找字符h的下标 8
-1
  • strip删除前后端的空格,换行符( ),制表符( 即”Tab“键),注意:当遇到不是清除的内容时,就会停下
x = '    

bright 	  	 
            '
print('原字符串:',x)
print('删除前后空的字符串:',x.strip())
原字符串:     

bright 	  	 
            
删除前后空的字符串: bright
x = 'xxxbrixghtxxx'
print('原字符串:',x)
print('删除两端的x:',x.strip('x'))
print('删除左端的x:',x.lstrip('x'))
print('删除右端的x:',x.rstrip('x'))
原字符串: xxxbrixghtxxx
删除两端的x: brixght
删除左端的x: brixghtxxx
删除右端的x: xxxbrixght
  • 分割字符串,构成列表;split() str(字符串)---> list(列表)
  • 将列表中的字符串,构成字符串输出:join() list(列表)---> str(字符串)
x = 'I am bright. how are you!'
print(x.split())   # 默认用空格分割
['I', 'am', 'bright.', 'how', 'are', 'you!']
x = '我,是,一个,军人,从,小,接受,锻炼。'
print(x.split(',')) # 采用逗号分割
['我', '是', '一个', '军人', '从', '小', '接受', '锻炼。']
x = 'Thank you, if you, I, will, choose, you.'
print(x.split(',', 2)) # 指定分割符,指定分割数量
['Thank you', ' if you', ' I, will, choose, you.']
x = ['bright']
print(x,type(x))
x_1 = '+'.join(x)
x_1
['bright'] <class 'list'>

'bright'
x = ['I','am','bright','.']
' '.join(x)
'I am bright .'
'$'.join(x)
'I$am$bright$.'
  • 替换 str.replace(被替换词,替换词,替换次数)
x = 'bright, bright, bright is bright'
print('bright的全部替换: ', x.replace('bright', 'sky'))
print('bright的首次替换: ', x.replace('bright', 'sky', 1))
print('bright的两次替换: ', x.replace('bright', 'sky', 2))
print('bright的三次替换: ', x.replace('bright', 'sky', 3))
bright的全部替换:  sky, sky, sky is sky
bright的首次替换:  sky, bright, bright is bright
bright的两次替换:  sky, sky, bright is bright
bright的三次替换:  sky, sky, sky is bright
  • 其它相关方法
    • 计算某些元素出现的个数 .count('搜索元素',起始位,终止位)

    • 判断字符串只由字母组成 .isalpha()

    • 判断字符串只由数字组成 .isdigit()

    • 判断字符串是由字母或数字组成组成的 .isalnum()