Python学习笔记4:列表、元组、字符串

一、列表

列表是有序集合,没有固定大小,能够保存任意数量任意类型的 Python 对象
[元素1, 元素2, ..., 元素n]

1.创建

  • 直接创建:
x=['a','b','c']
print(x,type(x))
# ['a','b','c'] <class 'list'>
  • 利用range()创建:
x=list(range(10))
print(x,type(x))
# [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] <class 'list'>

x=list(range(2,20,2))
print(x,type(x))
# [2, 4, 6, 8, 10, 12, 14, 16, 18] <class 'list'>
  • 利用推导式创建:
x=[1,2,3,4,5]*2
print(x,type(x))
# [1, 2, 3, 4, 5, 1, 2, 3, 4, 5] <class 'list'>

x=[i**2 for i in range(5)]
print(x,type(x))
# [0, 1, 4, 9, 16] <class 'list'>

x=[i for i in range(10) if (i%2==0)]
print(x,type(x))
# [0, 2, 4, 6, 8] <class 'list'>
  • 创建二维数组
x=[[1,2,3],[4,5,6],[7,8,9]]
print(x,type(x))
# [[1, 2, 3], [4, 5, 6], [7, 8, 9]] <class 'list'>
for i in x:
    print(i,type(i))
# [1, 2, 3] <class 'list'>
# [4, 5, 6] <class 'list'>
# [7, 8, 9] <class 'list'>

x[0][0] = 1
print(x, type(x))
# [[1, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0]] <class 'list'>

x = [[0] * 3 for row in range(4)]
print(x, type(x))
# [[0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0]] <class 'list'>

x[1][1] = 1
print(x, type(x))
# [[0, 0, 0], [0, 1, 0], [0, 0, 0], [0, 0, 0]] <class 'list'>

注意:
由于list的元素可以是任何对象,因此列表中所保存的是对象的指针。即使保存一个简单的[1,2,3],也有3个指针和3个整数对象。

x = [a] * 4操作中,只是创建4个指向list的引用,所以一旦a改变,x中4个a也会随之改变。

  • 创建混合列表
mix=[1,2,'abc',[1,2,3]]
print(mix,type(mix))
# [1, 2, 'abc', [1, 2, 3]] <class 'list'>
  • 创建空列表
x=[]
print(x,type(x))
# [] <class 'list'>

2.添加

  • list.append(obj) 在列表末尾添加新的对象,只接受一个参数,参数可以是任何数据类型,被追加的元素在 list 中保持着原结构类型。
x=['a','b','c']
x.append('d')
print(x)
# ['a', 'b', 'c', 'd']
print(len(x))
# 4

注意:添加元素如果是一个 list,那么这个 list 将作为一个整体进行追加。

x=['a','b','c']
x.append(['d','e'])
print(x)
# ['a', 'b', 'c', ['d', 'e']]
print(len(x))
# 4
  • list.extend(seq) 在列表末尾一次性追加另一个序列中的多个值(用新列表扩展原来的列表)
x.extend(['d','e'])
print(x)
# ['a', 'b', 'c', 'd', 'e']
print(len(x))
# 5

appendextend 的区别:
严格来说,append 是追加,把一个整体添加在列表后,而 extend 是扩展,把添加对象的所有元素添加在列表后。

  • list.insert(index,obj) 把对象插入位置 index
x=[1,2,4,5]
x.insert(2,3)
print(x)
# [1, 2, 3, 4, 5]

3.删除

  • list.remove(obj) 移除列表中某个值的第一歌匹配项
x=['a','b','c','d']
x.remove('b')
print(x)
# ['a', 'c', 'd']
  • list.pop(index) 移除列表中的某位置的元素,并返回该元素的值。(默认index=-1即最后一个元素)

注意:index 正值是从列表的首指针0开始往后逐个递加1的,负值是从列表的尾指针-1开始往前逐个递减1的。

x=[1,2,3,4,5,6,7,8,9]
y=x.pop()
print(y)
# 9
print(x)
# [1, 2, 3, 4, 5, 6, 7, 8]
z=x.pop(0)
print(z)
# 1
print(x)
# [2, 3, 4, 5, 6, 7, 8]
h=x.pop(3)
print(h)
# 5
print(x)
# [2, 3, 4, 6, 7, 8]

g=x.pop(-1)    
print(g)	    
# 8
print(x)	    
# [2, 3, 4, 6, 7]
s=x.pop(-2)
print(s)	    
# 6
print(x)	    
# [2, 3, 4, 7]

removepop 的区别:
remove 是指定要具体删除的元素,pop 是指定一个索引。

  • del list[var1:var2 ] 删除单个或多个对象
x=[1,2,3,4,5,6,7]
del x[3]
print(x)	    
# [1, 2, 3, 5, 6, 7]
del x[0:2]
print(x)	    
# [3, 5, 6, 7]

4.获取列表中的元素

  • 通过元素的索引值,从列表获取单个元素,注意,列表索引值是从0开始的。
  • 通过将索引指定为-1,可让Python返回最后一个列表元素,索引 -2 返回倒数第二个列表元素,以此类推。(负数是倒数)
x=[1,2,3,4,5,6]	    
print(x[0])	    
# 1
print(x[2])	    
# 3
print(x[-1])	    
# 6
print(x[-3])	    
# 4

切片的通用写法是:start:stop:step
缺少start则默认为列表头部,缺少stop则默认为列表尾部,缺少step则默认step为1。
所以 即获取所有元素

x=[1,2,3,4,5,6]
print(x[2:])    
# [3, 4, 5, 6]
print(x[-2:])
# [5, 6]
x=[1,2,3,4,5,6]
print(x[:3])
# [1, 2, 3]
print(x[:-2])
# [1, 2, 3, 4]
print(x[2:4])
# [3, 4]
print(x[-4:-2])
# [3, 4]
print(x[1:5:2])
# [2, 4]
print(x[:])
# [1, 2, 3, 4, 5, 6]
  • 浅拷贝与深拷贝
x=[1,3,9,6,8,7]
y=x
z=x[:]

print(y)
# [1, 3, 9, 6, 8, 7]
print(z)
# [1, 3, 9, 6, 8, 7]

x.sort()
print(y)
# [1, 3, 6, 7, 8, 9]
print(z)
# [1, 3, 9, 6, 8, 7]

x=[[123,456],[789,213]]
y=x
z=x[:]

print(y)
print(z)
# [[123, 456], [789, 213]]
# [[123, 456], [789, 213]]

x[0][0]=111
print(y)
print(z)
# [[111, 456], [789, 213]]
# [[111, 456], [789, 213]]

5.列表的常用操作符

  • 等号操作符==:只有成员、成员位置都相同时才返回True
  • 连接操作符 +:列表拼接,首尾相连
  • 重复操作符 *:列表拼接,复制拼接
  • 成员关系操作符innot in
list1 = [123, 456]
list2 = [456, 123]
list3 = [123, 456]

print(list1 == list2)  # False
print(list1 == list3)  # True

list4 = list1 + list2
print(list4)  # [123, 456, 456, 123]

list5 = list3 * 3
print(list5)  # [123, 456, 123, 456, 123, 456]

list3 *= 3
print(list3)  # [123, 456, 123, 456, 123, 456]

print(123 in list3)  # True
print(456 not in list3)  # False

前面三种方法append, extend, insert可对列表增加元素,是直接修改了原数据对象,没有返回值。 而将两个list相加,需要创建新的 list 对象,从而需要消耗额外的内存,特别是当 list 较大时,尽量不要使用 “+” 来添加list。

6.列表的其他方法

  • list.count(obj) 统计某个元素在列表中出现的次数。
list1 = [123, 456] * 3
print(list1)  # [123, 456, 123, 456, 123, 456]
num = list1.count(123)
print(num)  
# 3
  • list.index(x,start,end) 从列表中找出某个值 x 在范围start : end 内的第一个匹配项的索引位置。
list1 = [123, 456] * 5
print(list1)
# [123, 456, 123, 456, 123, 456, 123, 456, 123, 456]
print(list1.index(123))  
# 0
print(list1.index(123, 1))  
# 2
print(list1.index(123, 3, 7))  
# 4
  • list.reverse() 反向列表中元素。
x = [123, 456, 789]
x.reverse()
print(x)  
# [789, 456, 123]
  • list.sort(key=None, reverse=False) 对原列表进行排序(没有返回值)。
    key 主要是用来进行比较的元素,只有一个参数,具体的函数的参数就是取自于可迭代对象中,指定可迭代对象中的一个元素来进行排序。
    reverse 排序规则,reverse = True 降序, reverse = False 升序(默认)。
x = [123, 456, 789, 213]
x.sort()
print(x)
# [123, 213, 456, 789]
x.sort(reverse=True)
print(x)
# [789, 456, 213, 123]

# 获取列表的第二个元素
def takeSecond(elem):
    return elem[1]

x = [(2, 2), (3, 4), (4, 1), (1, 3)]
x.sort(key=takeSecond)
print(x)
# [(4, 1), (2, 2), (1, 3), (3, 4)]

x.sort(key=lambda a: a[0])
print(x)
# [(1, 3), (2, 2), (3, 4), (4, 1)]

练习题

1、列表lst = [2, 5, 6, 7, 8, 9, 2, 9, 9],请写程序完成下列操作:

  • 在列表的末尾增加元素15
  • 在列表的中间位置插入元素20
  • 将列表[2, 5, 6]合并到lst中
  • 移除列表中索引为3的元素
  • 翻转列表里的所有元素
  • 对列表里的元素进行排序,从小到大一次,从大到小一次
lst=[2,5,6,7,8,9,2,9,9]
lst.append(15)
print(lst)
# [2, 5, 6, 7, 8, 9, 2, 9, 9, 15]

L=len(lst)
n=int(L/2)
lst.insert(n,20)
print(lst)
# [2, 5, 6, 7, 8, 20, 9, 2, 9, 9, 15]

lst1=[2,5,6]
lst.extend(lst1)
print(lst)
# [2, 5, 6, 7, 8, 20, 9, 2, 9, 9, 15, 2, 5, 6]

lst.pop(3)
print(lst)
# [2, 5, 6, 8, 20, 9, 2, 9, 9, 15, 2, 5, 6]

lst.reverse()
print(lst)
# [6, 5, 2, 15, 9, 9, 2, 9, 20, 8, 6, 5, 2]

lst.sort()
print(lst)
# [2, 2, 2, 5, 5, 6, 6, 8, 9, 9, 9, 15, 20]
lst.sort(reverse=True)
print(lst)
# [20, 15, 9, 9, 9, 8, 6, 6, 5, 5, 2, 2, 2]

2、lst = [1, [4, 6], True],请将列表里所有数字修改成原来的两倍

def double_list(lst):
    for index,i in enumerate(lst):
        if isinstance(i,bool):
            continue
        if isinstance(i,(int,float)):
            lst[index]*=2
        if isinstance(i,list):
            double_list(i)
            
lst=[1,[4,6],True]
double_list(lst)
print(lst)

# [2, [8, 12], True]

3、LeetCode 852题 山脉数组的峰顶索引
在这里插入图片描述

  • 利用index()和max()函数
class Solution:
    def peakIndexInMountainArray(self, A: List[int]) -> int:
        return A.index(max(A))
  • 二分查找
class Solution:
    def peakIndexInMountainArray(self, A: List[int]) -> int:
        low,high=0,len(A)-1
        while low<high:
            mid=(low+high)//2
            if A[mid-1]<A[mid]<A[mid+1]:
                low=mid+1
            elif A[mid+1]<A[mid]<A[mid-1]:
                high=mid-1
            else:
                return mid
        return low

二、元组

(元素1,元素2,...,元素n)

元组和列表的异同:

  • Python 的元组与列表类似,不同之处在于元组被创建后就不能对其进行修改,类似字符串。
  • 元组使用小括号,列表使用方括号。
  • 元组与列表类似,也用整数来对它进行索引和切片。

1.创建和访问

  • 直接创建
    创建元组可以用小括号 (),也可以什么都不用,为了可读性,建议还是用 ()。
t=(1,2,3,'a','b','c')
print(t,type(t))
# (1, 2, 3, 'a', 'b', 'c') <class 'tuple'>

t=1,2,3,'a','b','c'
print(t,type(t))
# (1, 2, 3, 'a', 'b', 'c') <class 'tuple'>

t=(1,2,3,4,5,6,7)
print(t[2])
# 3
print(t[-1])
# 7
print(t[:])
(1, 2, 3, 4, 5, 6, 7)
print(t[2:5])
# (3, 4, 5)

注意:元组中只包含一个元素时,需要在元素后面添加逗号,否则括号会被当作运算符使用。

x=(1)
print(x,type(x))
# 1 <class 'int'>
x=(1,)
print(x,type(x))
# (1,) <class 'tuple'>
  • 利用推导式创建
x=5*(2,3)
print(x)
# (2, 3, 2, 3, 2, 3, 2, 3, 2, 3)
  • 创建二维元组
x=(1,2,3),('a','b','c')
print(x)
# ((1, 2, 3), ('a', 'b', 'c'))

print(x[0])
# (1, 2, 3)
print(x[0][0],x[1][1])
# 1 b

2.更新和删除

元组有不可更改 的性质,因此不能直接给元组的元素赋值,但是只要元组中的元素可更改,那么我们可以直接更改其元素。(这跟赋值其元素不同)

x = (1, 2, 3, [4, 5, 6])
print(x)  
# (1, 2, 3, [4, 5, 6])
x[3][0] = 9
print(x)  
# (1, 2, 3, [9, 5, 6])

3.元组的常用操作符

与列表基本相同

  • 等号操作符==:只有成员、成员位置都相同时才返回True
  • 连接操作符 +:列表拼接,首尾相连
  • 重复操作符 *:列表拼接,复制拼接
  • 成员关系操作符innot in
t1 = (123, 456)
t2 = (456, 123)
t3 = (123, 456)

print(t1 == t2)  
# False
print(t1 == t3)  
# True

t4 = t1 + t2
print(t4)  
# (123, 456, 456, 123)

t5 = t3 * 3
print(t5)  
# (123, 456, 123, 456, 123, 456)

t3 *= 3
print(t3)  
# (123, 456, 123, 456, 123, 456)

print(123 in t3)  
# True
print(456 not in t3)  
# False

4.内置方法

元组大小和内容都不可更改,因此只有countindex两种方法。

x=(1,2,3,1,2,3,1,2,3,4,'a')
print(x.count(2))
# 3
print(x.index('a'))
# 10

5.解压元组

  • 解压(unpack)一维元组(有几个元素左边括号定义几个变量)
x=(1,2,'word')
(a,b,c)=x
print(a,b,c)
# 1 2 word
  • 解压二维元组(按照元组里的元组结构来定义变量)
x=(1,2,3,('word','num'))
(a,b,c,(d,e))=x
print(a,b,c,(d,e))
# 1 2 3 ('word', 'num')
  • 如果你只想要元组其中几个元素,用通配符「*」,在计算机语言中代表一个或多个元素。
    当不需要rest变量时,可用下划线替代。
x=(1,2,3,4,5,6)
(a,b,*rest)=x
print(a,b)
# 1 2
print(rest)
# [3, 4, 5, 6]

练习题

1、元组概念
写出下面代码的执行结果和最终结果的类型
(1,2)*2
(1,)*2
(1)*2

x1=(1,2)*2
print(x1,type(x1))
# (1, 2, 1, 2) <class 'tuple'>
x2=(1,)*2
print(x2,type(x2))
# (1, 1) <class 'tuple'>
x3=(1)*2
print(x3,type(x3))
# 2 <class 'int'>

(1)*2是int类型,因为当元组只有一个元素的时候要多加一个逗号,否则括号就会变成运算符,式子就变成1*2

2、拆包过程是什么?a, b = 1, 2属于拆包吗?可迭代对象拆包时,怎么赋值给占位符?

拆包过程:利用赋值语句按顺序将元组中的各元素依次赋值给左边的各个变量。
a,b=1,2是变量的直接赋值,不属于拆包。
可迭代对象拆包时,保证变量的数量和可迭代对象元素的数量一致,对于不需要的元素可以用任意符号占位。

三、字符串

  • Python 中字符串被定义为引号之间的字符集合。
  • Python 支持使用成对的 单引号 或 双引号。

1.创建

x='hello world'
print(x,type(x))
# hello world <class 'str'>
x="hello world"
print(x,type(x))
# hello world <class 'str'>
x='2'+'4'
print(x,type(x))
# 24 <class 'str'>
  • Python的常用转义字符
转义字符名称
\\反斜杆符号
\'单引号
\"双引号
\n换行
\t横向制表符
\r回车

注意:如果字符串中需要出现单引号或双引号,可以使用转义符号\对字符串中的符号进行转义。

print('this\'s apple')
# this's apple
print("this's apple")
# this's apple
print('C:\\windows')
# C:\windows
print("C:\\windows\\program")
# C:\windows\program

原始字符串只需要在字符串前边加一个英文字母 r 即可。

print(r'C:\windows\program')
# C:\windows\program

三引号允许一个字符串跨多行,字符串中可以包含换行符、制表符以及其他特殊字符。

x="""aaaaaaa
bbbbbbb
1234567\n8
"""
print(x)
# aaaaaaa
# bbbbbbb
# 1234567
# 8

x='''aaaaaaa
bbbbbbb
1234567\n8
'''
print(x)
# aaaaaaa
# bbbbbbb
# 1234567
# 8

2.切片与拼接

  • 字符串类似于元组具有不可修改性
  • 切片通常写成 start:end 这种形式,包括start 对应的元素,不包括end对应的元素。
  • 索引值可正可负,正索引从 0 开始,从左往右递加1;负索引从 -1 开始,从右往左递减1。
str1='hello world'
print(str1[4])
# o
print(str1[6:])
# world
print(str1[:5])
# hello
print(str1[-2:])
# ld
str2=' Hey'
print(str1+str2)
# hello world Hey

3.字符串的常用内置方法

  • ==capitalize() ==将字符串的第一个字符转换为大写。
  • lower() 转换字符串中所有大写字符为小写。
  • upper() 转换字符串中的小写字母为大写。
  • swapcase() 将字符串中大写转换为小写,小写转换为大写。
str1='hello world'
print(str1.capitalize())
# Hello world
str2=str1.uppper()
print(str2)
# HELLO WORLD
print(str2.lower())
# hello world

str3='AaBbCc'
print(str3.swapcase())
# aAbBcC
  • count(str, start,end) 返回str在指定范围内出现的次数。
str1='apple pear orange'
print(str1.count('a'))
# 3
print(str1.count('a',0,len(str1)))
# 3
print(str1.count('a',2,9))
# 1
  • endswith(suffix, start=0, end=len(string)) 检查字符串是否以指定子字符串suffix 结束,如果是,返回 True,否则返回 False。如果 startend 指定值,则在指定范围内检查。
  • startswith(substr, beg=0,end=len(string)) 检查字符串是否以指定子字符串 substr 开头,如果是,返回 True,否则返回 False。如果 startend 指定值,则在指定范围内检查。
str1='apple pear orange'
print(str1.endswith('ge'))
# True
print(str1.endswith('ee'))
# False
print(str1.startswith('a'))
# True
  • find(str, start=0, end=len(string)) 检测 str 是否包含在字符串中,若包含则返回字符 str 开始的索引值,否则返回 -1。
  • rfind(str, start=0,end=len(string)) 类似于 find() 函数,不过是从右边开始查找。
str1='apple pear orange'
print(str1.find('pear'))
# 6
print(str1.find('tomato'))
# -1
print(str1.rfind('apple'))
# 0
print(str1.rfind('orange'))
# 11
  • isnumeric() 如果字符串中只包含数字字符,则返回 True,否则返回 False。
str1='25689'
print(str1.isnumeric())
# True
  • ljust(width[, fillchar]) 返回一个原字符串左对齐,并使用fillchar(默认空格)填充至长度width的新字符串。
  • rjust(width[, fillchar]) 返回一个原字符串右对齐,并使用fillchar(默认空格)填充至长度width的新字符串。
str1='abc'
print(str1.ljust(6,'*'))
# abc***
print(str1.rjust(6,'*'))
# ***abc
  • lstrip([chars]) 删除字符串左边的空格或指定字符。
  • rstrip([chars]) 删除字符串末尾的空格或指定字符。
  • strip([chars]) 在字符串上执行lstrip()和rstrip()。
str1=' hello world ! '
print(str1.lstrip())
# hello world ! 
# print(str1.rstrip())
#  hello world !
print(str1.strip().strip())
# hello world !
print(str1.strip().strip('!'))
# hello world 
  • partition(sub) 找到子字符串sub,把字符串分为一个三元组(pre_sub,sub,fol_sub),如果字符串中不包含sub则返回(‘原字符串’,’’,’’)。
  • rpartition(sub) 类似于partition()方法,不过是从右边开始查找。
str1='apple pear orange peach plum'
print(str1.partition('p'))
# ('a', 'p', 'ple pear orange peach plum')
print(str1.rpartition('p'))  
# ('apple pear orange peach ', 'p', 'lum')
print(str1.partition('k'))  
# ('apple pear orange peach plum', '', '')
  • ==replace(old, new, max) == 把 将字符串中的old替换成new,如果max指定,则替换不超过max次。
str1='apple pear orange peach plum'
print(str1.replace('a','A'))  
# Apple peAr orAnge peAch plum
print(str1.replace('a','A',3))	  
# Apple peAr orAnge peach plum
  • split(str="", num) 不带参数默认是以空格为分隔符切片字符串,如果num参数有设置,则仅分隔num个子字符串,返回切片后的子字符串拼接的列表。
str1='apple pear orange peach plum'
print(str1.split())  
# ['apple', 'pear', 'orange', 'peach', 'plum']
print(str1.split('p'))
# ['a', '', 'le ', 'ear orange ', 'each ', 'lum']
print(str1.split('p',3))  
# ['a', '', 'le ', 'ear orange peach plum']

u = "www.baidu.com.cn"
print((u.split('.')))  
# ['www', 'baidu', 'com', 'cn']
print((u.split(".", 2)[1]))  # 分割两次,并取序列为1的项
# baidu
u1, u2, u3 = u.split(".", 2)  # 分割两次,并把分割后的三个部分保存到三个变量
print(u1)  # www
print(u2)  # baidu
print(u3)  # com.cn

string = "hello boy<[www.baidu.com]>byebye"
print(string.split('[')[1].split(']')[0])  
# www.baidu.com
print(string.split('[')[1].split(']')[0].split('.'))  
# ['www', 'baidu', 'com']
  • splitlines([keepends]) 按照行(’\r’, ‘\r\n’, \n’)分隔,返回一个包含各行作为元素的列表,如果参数keepends为 False,不包含换行符,如果为 True,则保留换行符。
str1='hello \n world \n !'
print(str1.splitlines())
# ['hello ', ' world ', ' !']
print(str1.splitlines(True))
# ['hello \n', ' world \n', ' !']
  • maketrans(intab, outtab) 创建字符映射的转换表,intab 是字符串,表示需要转换的字符,outtab 也是字符串表示转换的目标。
  • translate(table, deletechars="") 根据参数 table 给出的表,转换字符串的字符,要过滤掉的字符放到 deletechars 参数中。
str1 = 'this is string example....wow!!!'
intab = 'aeiou'
outtab = '12345'
trantab = str1.maketrans(intab, outtab)
print(trantab)  
# {97: 49, 111: 52, 117: 53, 101: 50, 105: 51}
print(str1.translate(trantab))  
# th3s 3s str3ng 2x1mpl2....w4w!!!

4.字符串格式化

  • format() 格式化函数
str1 = "{0} Love {1}".format('I', 'China')  # 位置参数
print(str1)  
# I Love China
str1 = "{a} Love {b}".format(a='I', b='China')  # 关键字参数
print(str1)  
# I Love China
str1 = "{0} Love {b}".format('I', b='China')  # 位置参数要在关键字参数之前
print(str1)  
# I Love China
str1 = '{0:.2f}{1}'.format(3.2568, 'm')  # 保留小数点后两位
print(str1)  # 3.26m
  • 字符串格式化符号
符号描述
%c格式化字符及其ASCII码
%s格式化字符串,用str()方法处理对象
%r格式化字符串,用rper()方法处理对象
%d格式化整数
%o格式化无符号八进制数
%x格式化无符号十六进制数
%X格式化无符号十六进制数(大写)
%f格式化浮点数字,可指定小数点后的精度
%e用科学计数法格式化浮点数
%E作用同%e,用科学计数法格式化浮点数
%g根据值的大小决定使用%f或%e
%G作用同%g,根据值的大小决定使用%f或%E
print('%c' % 97)  # a
print('%c %c %c' % (97, 98, 99))  # a b c
print('%d + %d = %d' % (4, 5, 9))  # 4 + 5 = 9
print("我叫%s,今年%d岁!" % ('小明', 10))  # 我叫小明,今年10岁!
print('%o' % 10)  # 12
print('%x' % 10)  # a
print('%X' % 10)  # A
print('%f' % 27.658)  # 27.658000
print('%e' % 27.658)  # 2.765800e+01
print('%E' % 27.658)  # 2.765800E+01
print('%g' % 27.658)  # 27.658
text = "I am %d years old." % 10
print("I said: %s." % text)  
# I said: I am 10 years old.
print("I said: %r." % text)  
# I said: 'I am 10 years old.'
  • 格式化操作符辅助指令
符号功能
m.nm 是显示的最小总宽度,n 是小数点后的位数(如果可用的话)
-用作左对齐
+在正数前面显示加号( + )
#在八进制数前面显示零(‘0’),在十六进制前面显示’0x’或者’0X’(取决于用的是’x’还是’X’)
0显示的数字前面填充’0’而不是默认的空格
print('%5.1f' % 27.658)  # ' 27.7'
print('%.2e' % 27.658)  # 2.77e+01
print('%10d' % 10)  # '        10'
print('%-10d' % 10)  # '10        '
print('%+d' % 10)  # +10
print('%#o' % 10)  # 0o12
print('%#x' % 108)  # 0x6c
print('%010d' % 5)  # 0000000005

练习题

1、字符串函数回顾

  • 怎么批量替换字符串中的元素?
    使用replace(old, new)函数。
  • 怎么把字符串按照空格进⾏拆分?
    使用str.split(str="", num)函数。
  • 怎么去除字符串⾸位的空格?
    使用str.lstrip() 函数。

2、实现函数isdigit, 判断字符串里是否只包含数字0~9

def isdigit(str1):
    for i in str1:
        if i>='0' and i<='9':
            flag=0
            continue
        else:
            flag=1
            print('该字符串不只包含数字0~9')
            break
    else:
        print('该字符串只包含数字0~9')

str1=input("请输入字符串:")
isdigit(str1)

请输入字符串:26989564
#该字符串只包含数字0~9
请输入字符串:sbv59592
#该字符串不只包含数字0~9

3、leetcode 5题 最长回文子串
在这里插入图片描述

class Solution:
    def longestPalindrome(self, s: str) -> str:
        if len(s)<=1000:
            l=len(s)-1
            str1=s
            c=0
            for i in range(l):
                n=c
                start=i
                left=i
                right=l
                c,k=0,0
                while left<right:
                    if s[left]!=s[right]:
                        k+=1
                        right=l-k
                        left=i
                        c=0
                        continue
                    else:
                        left+=1
                        right-=1
                        c+=2
                if left==right:
                    c=c+1
                end=start+c
                if c>n:
                    str1=s[start:end]
                else:
                    c=n
            return str1

# 暴力解法,当s长度为1000时,超时了


'''
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值