-
format字符串嵌套{}查看全部
-
pyhon之嵌套循环
像多层if-else嵌套一样,python的循环也支持嵌套。
我们使用两层嵌套循环输出字符串'ABC'中每个字符和字符串'123'每个字符的排列。s1 = 'ABC'
s2 = '123'
for x in s1:
for y in s2:
print(x + y)在上述代码中,对于外层循环,外层每循环1次,内层就会循环3次。
查看全部 -
python之continue继续循环
使用continue,我们可以控制循环继续下去,并跳过continue后面的逻辑。
查看全部 -
Python之break跳出循环
用 for 循环或者 while 循环时,如果要在循环体内直接退出循环,可以使用 break 语句。
比如在前面的无限循环里面,只要在恰当的时机,我们使用break跳出循环,也可以求出1~100的和。num = 1 sum = 0 while True: if num > 100: break sum = sum + num num = num + 1 print(sum)
查看全部 -
Python之for循环
计算平均分数
L = [75, 92, 59, 68, 99]
sum = 0.0
for x in L:
sum=sum + x
print(sum/5)
###########################################
s = 'ABCD'
for ch in s:
print(ch) # 注意缩进在上述代码中,ch是在for循环中定义的,意思是把字符串s中的每一个元素依次赋值给ch,然后再把ch打印出来,直到打印出字符串s的最后一个字符为止。
查看全部 -
Python的字符串切片###中括号取字符【】###
'ABC',第一个字符是A,第二个字符是B,第三个字符是C
不过需要注意的是,在程序的世界中,计数是从0开始的,使用0来表示第一个。
s = 'ABC'
a = s[0] # 第一个
b = s[1] # 第二个
c = s[2] # 第三个
print(a) # ==> A
print(b) # ==> B
print(c) # ==> C有时候,我们会想获取字符串的一部分(子串),这个时候我们采取切片的方式获取,切片需要在中括号[]中填入两个数字,中间用冒号分开,表示子串的开始位置和结束位置,并且这是半闭半开区间,不包括最后的位置。
ab = s[0:2] # 取字符串s中的第一个字符到第三个字符,不包括第三个字符
print(ab) # ==> AB查看全部 -
Python的字符串format
format由两个部分组成,{字符串模板}和{模板数据}内容组成,通过大括号{},就可以把模板数据内容嵌到字符串模板对应的位置。
# 字符串模板
template = 'Hello {}'
# 模板数据内容
world = 'World'
result = template.format(world)
print(result) # ==> Hello World
如果模板中{}比较多,则容易错乱,那么在format的时候也可以指定模板数据内容的顺序。# 指定顺序
template = 'Hello {0}, Hello {1}, Hello {2}, Hello {3}.'
result = template.format('World', 'China', 'Beijing', 'imooc')
print(result) # ==> Hello World, Hello China, Hello Beijing, Hello imooc.# 调整顺序##白话就是大括号倒置##
template = 'Hello {3}, Hello {2}, Hello {1}, Hello {0}.'
result = template.format('World', 'China', 'Beijing', 'imooc')
print(result) # ==> Hello imooc, Hello Beijing, Hello China, Hello World.# 指定{}的名字w,c,b,i#####模板数据要赋值#####
template = 'Hello {w}, Hello {c}, Hello {b}, Hello {i}.'
world = 'World'
china = 'China'
beijing = 'Beijing'
imooc = 'imooc'
# 指定名字对应的模板数据内容
result = template.format(w = world, c = china, b = beijing, i = imooc)
print(result) # ==> Hello World, Hello China, Hello Beijing, Hello imooc.查看全部 -
如果一个字符串包含很多需要转义的字符,对每一个字符都进行转义会很麻烦。为了避免这种情况,我们可以在字符串前面加个前缀r,表示这是一个 raw 字符串,里面的字符就不需要转义了
查看全部 -
我们只想要 dict 的 key,不关心 key 对应的 value,目的就是保证这个集合的元素不会重复,
查看全部 -
s1 = set([1, 2, 3, 4, 5])
s2 = set([1, 2, 3, 4, 5, 6, 7, 8, 9])
for s in s1:
if s1.isdisjoint(s2):
break
else:
if s in s2:
print s
s2.remove(s)
查看全部 -
取模是什么意思
99/3
查看全部 -
这里m=m+1放在前面有没有影响查看全部
-
python之break跳出循环
用 for 循环或者 while 循环时,如果要在循环体内直接退出循环,可以使用 break 语句。
查看全部 -
python之while循环
while循环可以继续进行下去的条件更加简单,只需要判断while循环的条件是否为True即可,当条件为True时,即继续运行下去。
把while循环的条件设置得复杂一些,在运行一定次数后,条件可以自动变为False从而跳出while循环。
查看全部 -
python之for循环
s = 'ABCD'
for ch in s:
print(ch) # 注意缩进在上述代码中,ch是在for循环中定义的,意思是把字符串s中的每一个元素依次赋值给ch,然后再把ch打印出来,直到打印出字符串s的最后一个字符为止。
查看全部
举报