Python字符和列表怎么表示(python,编程语言)

时间:2024-04-29 09:12:41 作者 : 石家庄SEO 分类 : 编程语言
  • TAG :

Python字符和列表怎么表示

1.字符串

字符串表现形式

a="100"b="helloworld"c='helloworld'd='100'e=‘18.20520'

1.1len函数返回对象的长度或者个数

Python len( )方法返回对象(字符、列表、元组、字典等)长度或项目个数。

In[1]:a="abcdefg"In[2]:len(a)Out[2]:7In[3]:b=[1,2,3,4,5,66,77,8888]In[4]:len(b)Out[4]:8

1.2组成字符串的另外一种方式:

字符串会拼接,数字会相加

In[5]:a="lao"In[6]:b="wang"In[7]:c=a+bIn[8]:cOut[8]:'laowang'In[9]:d="===="+a+b+"===="In[10]:dOut[10]:'====laowang===='In[11]:f="===%s===="%(a+b)In[12]:fOut[12]:'===laowang===='

2.字符串的输入输出

2.1字符串输入

输入信息

name=input(“请输入你的姓名:”)position=input(“请输入你的职业:”)address=input(“请输入你的地址:”)

输出信息

print("="*50)print("姓名:%s\n职业:%s\n地址:%s"%(name,position,address))print("="*50)

2.2format的使用语法:

格式化的方式展示数据,并可以通过多种方式展示数据。如 通过位置、通过关键字参数、通过映射list。

1.通过位置
print(“my name is {0},age is {1}”.format(‘刘备’,20))
print(“my name is {},age is {}”.format(‘刘备’,20))
print(“{1},{0},{1}”.format(‘刘备’,20))
2.通过关键字参数
print(“{age},{name}”.format(age=28,name=“曹操”))
print(“{name},{name},{age}”.format(age=28,name=“曹操”))
3.通过映射list
alist = [“孙权”,20,“中国”]
blist = [“貂蝉”,18,“中国”]
print(“my name is {1[0]}, from {0[2]}, age is {0[1]}”.format(alist,blist))

在python3中input 获取的数据,都以字符串的方式进行保存,即使输入的是数字,那么也是以字符串方式保存

#判断密码是否正确

user_name=input(“请输入用户名:”)password=input(“请输入密码:”)ifuser_name==“beijing”andpassword==“123”:print(“欢迎登录北京官网!")else:print("你的账户或者密码错误!")

2.3下标介绍

下标索引 index
所谓“下标”,就是编号,就好比超市中的存储柜的编号,通过这个编号就能找到相应的存储空间。
通过下标取出部分字符
如果有字符串:name = ‘abcdef’,在内存中的实际存储如下:
Python字符和列表怎么表示

In [1]: len(name)
Out[1]: 7
In [2]: name[len(name)-1]
Out[2]: ‘g’
In [3]: name[-1]
Out[3]: ‘g’ 正数从左往右,负数从右往左

2.4切片

切片是指对操作的对象截取其中一部分的操作。字符串、列表、元组都支持切片操作。
切片的语法:[ 起始: 结束: 步长]
注意:选取的区间属于 左闭右开型,即从"起始"位开始,到"结束"位的前一位结束(不包含结束位本身),注意,如果不写步长默认是1.
步长是控制方向的,正数从左往右取,负数是从右到左取

In[1]:name="abcdefABCDEF"In[2]:name[0:3]Out[2]:'abc'In[3]:name[0:5:2]Out[3]:'ace'In[4]:name[-1::-1] #逆序(倒叙)Out[4]:'FEDCBAfedcba'

下标和切片小结
[:] 提取从开头(默认位置0)到结尾的整个字符串
[start:] 从start 提取到结尾
[:end] 从开头提取到end - 1
[start:end] 从start 提取到end - 1
[startstep] 从start 提取到end - 1,每step 个字符提取一个
[::-1]逆序

3.字符串常见函数

find()、 rfind ()、 index ()、 rindex ()、 replace ()、split ()、parttion ()、rparttion ()、splitlines ()、startswith ()、endswith ()、lower ()、upper ()、…………

3.1find及rfind

In[1]:mystr="helloworldyanziluandyanziluPython"In[2]:mystrOut[2]:'helloworldyanziluandyanziluPythonIn[3]:mystr.find("and")Out[3]:20In[4]:mystr.find("world") #存在则返回该单词开始的下标Out[4]:6In[5]:mystr.find("world1") #不存在则返回-1Out[5]:-1In[6]:mystr.find("yanzilu")Out[6]:12In[7]:mystr.find("yanzilu",20,len(mystr))#指定查找区域Out[7]:24In[8]:mystr.rfind("yanzilu") #rfind,从右往左搜索Out[8]:24

3.2index 、rindex

作用和find一样,只有一点不同,index搜索不到的内容会报错

In[9]:mystr.index("and")Out[9]:20In[10]:mystr.index("yanzilu")Out[10]:12In[11]:mystr.index("yanzilu",20,len(mystr)) #指定查找区域Out[11]:24In[12]:mystr.rindex("yanzilu") #从右往左搜索Out[12]:24In[13]:mystr.rindex("zhangsan") #搜索不存在的会报错---------------------------------------------------------------------------ValueErrorTraceback(mostrecentcalllast)<ipython-input-67-6aff7ee60ad5>in<module>---->1mystr.rindex("zhangsan")ValueError:substringnotfound

3.3 replace 替换

In[14]:mystrOut[14]:'helloworldyanziluandyanziluPython'In[15]:mystr.replace("world","WORLD")Out[15]:'helloWORLDyanziluandyanziluPython'In[16]:mystrOut[16]:'helloworldyanziluandyanziluPython'In[17]:mystr.replace("yan","zhang")Out[17]:'helloworldzhangziluandzhangziluPython'In[18]:mystr.replace("yan","zhang",1) #指定替换次数Out[18]:'helloworldzhangziluandyanziluPython'In[19]:mystr.replace("yan","xxx",1)Out19]:'helloworldxxxziluandyanziluPython'In[20]:mystr.replace("yan","xxx",2)Out[20]:'helloworldxxxziluandxxxziluPython'In[21]:mystr.replace("yan","xxx",33) #替换次数可以超过最大值Out[21]:'helloworldxxxziluandxxxziluPython'

3.4split,作用分割,切割 ,语法:split(str=’ ',maxsplit)

In[22]:mystrOut[22]:'helloworldyanziluandyanziluPython'In[23]:mystr.split("")Out[23]:['hello','world','yanzilu','and','yanziluPython']In[24]:mystr.split("and")Out[24]:['helloworldyanzilu','yanziluPython']In[25]:mystr.split("",3)Out[25]:['hello','world','yanzilu','andyanziluPython']In[26]:mystr.split()Out[26]:['hello','world','yanzilu','and','yanziluPython']

3.5 partition , 把mystr 以str分割成三个部分,str前,str自身,str后

In[27]:mystrOut[27]:'helloworldyanziluandyanziluPython'In[28]:mystr.partition("and")Out[28]:('helloworldyanzilu','and','yanziluPython')In[29]:mystr.partition("yanzilu")Out[29]:('helloworld','yanzilu','andyanziluPython')In[30]:mystr.rpartition("yanzilu")Out[30]:('helloworldyanziluand','yanzilu','Python')

3.6splitlines作用,按照行进行分割,返回一个包含各行作为元素的列表

In[31]:mystr1Out[31]:'hello\nworld\nyanzilu\nand\nyanziluPython'In[32]:mystr1.splitlines()Out[32]:['hello','world','yanzilu','and','yanziluPython']

3.7 startswith () 判断是否以str开头; endswith () 判断是否以str结尾。

In[33]:mystrOut[33]:'helloworldyanziluandyanziluPython'In[34]:mystr.startswith("hello")Out[34]:TrueIn[35]:mystr.startswith("Hello")Out[35]:FalseIn[36]:mystr.startswith("h")Out[36]:TrueIn[37]:mystr.endswith("Pthon")Out[37]:FalseIn[38]:mystr.endswith("Python")Out[38]:True

3.8upper将所有字母转换为大写; lower将所有字母转换为小写。

In[39]:mystr.upper()。Out[39]:'HELLOWORLDYANZILUANDYANZILUPYTHON'In[40]:mystr.lower()Out[40]:'helloworldyanziluandyanzilupython'

3.9center给字符串两边添加空格,居中显示

In[41]:mystr="那一夜我伤害了你"In[42]:mystr=mystr.center(30)In[43]:mystrOut[43]:'那一夜我伤害了你

###3.10 lstrip删除字符串左边的空格

In[44]:mystr.lstrip()Out[44]:'那一夜我伤害了你

3.11rstrip删除字符串右边的空格

In[45]:mystr.rstrip()Out[45]:'那一夜我伤害了你'

3.12 strip删除字符串两边的空格

In[46]:mystr.strip()Out[46]:'那一夜我伤害了你'

3.13isspace判断是否只包含空格

In[47]:mystr.isspace()Out[47]:FalseIn[48]:mystr=""In[49]:mystr.isspace()Out[49]:True

3.14salpha判断字符串中是否只包含字母

In[50]:mystr="abc"In[51]:mystr.isalpha()Out[51]:TrueIn[52]:mystr="abc1"In[53]:mystr.isalpha()Out[53]:False

3.15isdigit判断是否只包含数字。

In[54]:mystr="123123"In[55]:mystr.isdigit()Out[55]:TrueIn[56]:mystr="123123aa"In[57]:mystr.isdigit()Out[57]:False

3.16isalnum判断是否只包含数字和字母。

In[58]:mystr.isalnum()Out[58]:TrueIn[59]:mystr="123123aa"In[60]:mystr.isalnum()Out[60]:False

3.17title将每个单词的首字母大写,其余小写

In[61]:mystr='helloworldyanziluandyanziluPython'In[62]:mystr.title()Out[63]:'HelloWorldYanziluAndYanzilupython'

3.18capitalize将字符串的第一个字符大写,其余小写

In[64]:mystr.capitalize()Out[64]:'Helloworldyanziluandyanzilupython'

3.19count统计单词出现的次数

In[65]:mystr.count("hello")Out[65]:1In[66]:mystr.count("yan")Out[66]:2

3.20join在每个字符后面插入str,构造出一个新的字符串。

In[67]:mystr=""In[68]:nameOut[68]:['hello','world','yanzilu','and','yanziluPython']In[69]:mystr.join(name)Out[69]:'helloworldyanziluandyanziluPython'In[70]:mystr="_"In[71]:mystr.join(name)Out[71]:'hello_world_yanzilu_and_yanziluPython'

4.列表及循环遍历

4.1列表的格式

#变量names_list的类型为列表names_list=['刘备','曹操','孙权']#打印多个姓名names_list=['刘备','曹操','孙权']print(names_list[0])print(names_list[1])print(names_list[2])names=['刘备','曹操','孙权']forxinnamesprint(x)i=1whilei<len(names)print(name[i])i+=1

5.列表的增删改查:

列表中存放的数据是可以进行修改的,比如"增"、“删”、“改”

5.1列表的添加元素("增"append, extend, insert)

append可以向列表添加元素
extend将另一个集合中的元素逐一添加到列表中
insert在指定位置index前插入元素

name=[“刘备”,”曹操”,”孙权”]print(“增加之前:”,name)info=[“黄忠”,”魏延”]

append追加

names.append("吕布")names.append("貂蝉")names.append(info) #append把中括号也增加上了print("增加之后:",names)

这里是引用

使用extend合并列表

info=["黄忠","魏延"]names.extend(info)print("增加之后:",names)

这里是引用

insert在指定位置前插入元素

names.insert(0,"刘禅")print("增加之后:",names)

5.2删除元素 (" 删 "del, pop, remove)

del根据下标进行删除
pop删除最后一个元素
remove根据元素的值进行删除

names=['刘备','曹操','孙权','吕布','貂蝉','黄忠','魏延']print("删除前:",names)

5.3del指定下标删除

delnames[1]print("del删除后:",names)

5.4使用pop删除最后一个元素

names.pop()names.pop()print("pop删除后:",names)

5.5使用remove根据元素值进行删除

name=input("请输入您要删除的历史人物:")names.remove(name)print("remove删除后:",names)

5.6列表的修改

通过下标修改元素 (" 改 ")

names=["刘备","曹操","孙权"]names[0]="刘禅"print(names)

5.7查找元素("查"in, not in, index, count)

python中查找的常用方法为:
in (存在), 如果存在那么结果为True ,否则为False
not in (不存在),如果不存在那么结果为True ,否则False
index和count与字符串中的用法相同

names=['刘备','曹操','孙权','吕布','貂蝉','黄忠','魏延',"曹操"]findName=input("请输入您要查找的姓名:")iffindNameinnames:print("已经找到:%s"%findName)else:print("没有找到:%s"%findName)
In[1]:names=['刘备','曹操','孙权','吕布','貂蝉','黄忠','魏延',’曹操’]In[2]:name.index(“曹操”)Out[2]:1In[3]:name.index(“曹操”,2,leb(names))Out[3]:7In[4]:name.count(“曹操”)Out[4]:2

6.排序(sort, reverse)

sort方法是将list按特定顺序重新排列,默认为由小到大(True:从小到大;False从大到小)
reverse=True可改为倒序,由大到小。
reverse方法是将list逆置。需要先排序再降序

7.列表嵌套

类似while循环的嵌套,列表也是支持嵌套的一个列表中的元素又是一个列表,那么这就是列表的嵌套
示例:

school_names=[['北京大学','清华大学'],['南开大学','天津大学'],['贵州大学','青海大学']]print(school_names)
#print(school_names)#print(len(school_names))#print(school_names[2][1])forschoolinschool_names:print("="*30)print(school)fornameinschool:print(name)

8.列表嵌套的应用- - 随机安排老师工位

一个学校,有3个办公室,现在有8位老师等待工位的分配,请编写程序,完成随机的分配

importrandomoffices=[[],[],[]]names=['刘备','曹操','孙权','吕布','貂蝉','黄忠','魏延','大乔']forofficeinoffices:#得到一个教师的下标index=random.randint(0,len(names)-1)#分配老师name=names[index]office.append(name)#要移除已经完成分配的老师names.remove(name)fornameinnames:#得到办公室编号index=random.randint(0,2)offices[index].append(name)#print(offices)#打印出来哪些办公室有哪些老师i=1forofficeinoffices:#office=["刘备","曹操"]print("办公室%s:共%s人"%(i,len(office)))i+=1fornameinoffice:print("%s"%name,end="\t\t")print()print("="*30)
 </div> <div class="zixun-tj-product adv-bottom"></div> </div> </div> <div class="prve-next-news">
本文:Python字符和列表怎么表示的详细内容,希望对您有所帮助,信息来源于网络。
上一篇:jquery对象访问的方法是什么下一篇:

7 人围观 / 0 条评论 ↓快速评论↓

(必须)

(必须,保密)

阿狸1 阿狸2 阿狸3 阿狸4 阿狸5 阿狸6 阿狸7 阿狸8 阿狸9 阿狸10 阿狸11 阿狸12 阿狸13 阿狸14 阿狸15 阿狸16 阿狸17 阿狸18