join用法与for循环用法

一:join用法

字符串迭代添加元素

s='dsfhhewfe'
s1='*'.join(s)
print(s1)

打印结果:

d*s*f*h*h*e*w*f*e

160022_Zyfo_3657436.png

二:字符串循环(与for循环连用,可以添加break,continue)

1 for循环与break连用

for i in s:
    if i=='h':
        break
    print(i)

打印结果

160503_iM5t_3657436.png

2  for循环与continue连用

for i in s:
    if i=='h':
        continue
    print(i)

打印结果

161002_y2vm_3657436.png

 

三:while与else连用

while 1:
    pass
else:
    pass

四:for与else连用

s='alkshfdfhg'
for i in s:
    if i=='h':
       continue
    print(i)
else:
    print('666')

打印结果

161220_gXLf_3657436.png

 

以下是网上找的:

Python for循环的使用

(一)for循环的使用场景

1.如果我们想要某件事情重复执行具体次数的时候可以使用for循环。 
2.for循环主要用来遍历、循环、序列、集合、字典,文件、甚至是自定义类或函数。

(二)for循环操作列表实例演示

  1. 使用for循环对列表进行遍历元素、修改元素、删除元素、统计列表中元素的个数。

1.for循环用来遍历整个列表

#for循环主要用来遍历、循环、序列、集合、字典
Fruits=['apple','orange','banana','grape']
for fruit in Fruits:
    print(fruit)
print("结束遍历")
  • 1
  • 2
  • 3
  • 4
  • 5
结果演示:
    apple
    orange
    banana
    grape
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

2.for循环用来修改列表中的元素

#for循环主要用来遍历、循环、序列、集合、字典
#把banana改为Apple
Fruits=['apple','orange','banana','grape']
for i in range(len(Fruits)):
    if Fruits[i]=='banana':
        Fruits[i]='apple'
print(Fruits)
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
结果演示:['apple', 'orange', 'apple', 'grape']
  • 1
  • 2

3.for循环用来删除列表中的元素

Fruits=['apple','orange','banana','grape']
for i in  Fruits:
    if i=='banana':
        Fruits.remove(i)
print(Fruits)
  • 1
  • 2
  • 3
  • 4
  • 5
结果演示:['apple', 'orange', 'grape']
  • 1
  • 2

4.for循环统计列表中某一元素的个数

#统计apple的个数
Fruits=['apple','orange','banana','grape','apple']
count=0
for i in  Fruits:
    if i=='apple':
        count+=1
print("Fruits列表中apple的个数="+str(count)+"个")
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
结果演示:Fruits列表中apple的个数=2个

注:列表某一数据统计还可以使用Fruit.count(object)
  • 1
  • 2
  • 3
  • 4

5.for循环实现1到9相乘

sum=1
for i in list(range(1,10)):
    sum*=i
print("1*2...*10="+str(sum))
  • 1
  • 2
  • 3
  • 4
结果演示:1*2...*10=362880
  • 1

6.遍历字符串

for str in 'abc':
    print(str)
  • 1
  • 2
  • 3
结果演示:
a
b
c
  • 1
  • 2
  • 3
  • 4

7.遍历集合对象

for str in {'a',2,'bc'}:
    print(str)
  • 1
  • 2
  • 3
结果演示:
a
2
bc
  • 1
  • 2
  • 3
  • 4
  • 5

8.遍历文件

for content in open("D:\\test.txt"):
    print(content)
  • 1
  • 2
  • 3
结果演示:
朝辞白帝彩云间,千里江陵一日还。

两岸猿声啼不住,轻舟已过万重山。
  • 1
  • 2
  • 3
  • 4

9.遍历字典

for key,value in {"name":'Kaina',"age":22}.items():
    print("键---"+key)
    print("值---"+str(value))
  • 1
  • 2
  • 3
结果演示:
键---name
值---Kaina
键---age
值---22

转载于:https://my.oschina.net/u/3648651/blog/1802358

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值