首页 > > > 6个实例,8段代码,详解Python中的for循环
公众号后台回复“图书“,了解更多号主新书内容




line = '1 2 3 4 10e abc'
sum =
invalidStr = ""
print('String of numbers:',line)
for str in line.split(" "):
try:
sum = sum + eval(str)
except:
invalidStr = invalidStr + str + ' '
print('sum:', sum)
if(invalidStr != ""):
print('Invalid strings:',invalidStr)
else:
print('All substrings are valid numbers')

maxPower = 4
maxCount = 4
def pwr(num):
prod = 1
for n in range(1,maxPower+1):
prod = prod*num
print(num,'to the power',n, 'equals',prod)
print('-----------')
for num in range(1,maxCount+1):
pwr(num)

max = 8
for x in range(1,max+1):
for y in range(1,x+1):
print(y,'', end='')
print()

x = 'This is a string that contains abc and Abc'
y = 'abc'
identical =
casematch =
for w in x.split():
if(w == y):
identical = identical + 1
elif (w.lower() == y.lower()):
casematch = casematch + 1
if(identical > ):
print('found identical matches:', identical)
if(casematch > ):
print('found case matches:', casematch)
if(casematch == and identical == ):
print('no matches found')

import string
wordCount =
str1 = 'this is a string with a set of words in it'
print('Left-justified strings:')
print('-----------------------')
for w in str1.split():
print('%-10s' % w)
wordCount = wordCount + 1
if(wordCount % 2 == ):
print("")
print("\n")
print('Right-justified strings:')
print('------------------------')
wordCount =
for w in str1.split():
print('%10s' % w)
wordCount = wordCount + 1
if(wordCount % 2 == ):
print()

import string
left =
right =
columnWidth = 8
str1 = 'this is a string with a set of words in it and it will be split into a fixed column width'
strLen = len(str1)
print('Left-justified column:')
print('----------------------')
rowCount = int(strLen/columnWidth)
for i in range(,rowCount):
left = i*columnWidth
right = (i+1)*columnWidth-1
word = str1[left:right]
print("%-10s" % word)
# check for a 'partial row'
if(rowCount*columnWidth < strLen):
left = rowCount*columnWidth-1;
right = strLen
word = str1[left:right]
print("%-10s" % word)

text1 = 'a b c d'
text2 = 'a b c e d'
if(text2.find(text1) >= ):
print('text1 is a substring of text2')
else:
print('text1 is not a substring of text2')
subStr = True
for w in text1.split():
if(text2.find(w) == -1):
subStr = False
break
if(subStr == True):
print('Every word in text1 is a word in text2')
else:
print('Not every word in text1 is a word in text2')

text = 'abcdef'
for ch in text:
print('char:',ch,'ord value:',ord(ch))
print





划重点👇
◆ ◆ ◆ ◆ ◆
麟哥新书已经在当当上架了,我写了本书:《拿下Offer-数据分析师求职面试指南》,目前当当正在举行活动,大家可以用相当于原价5折的预购价格购买,还是非常划算的:
数据森麟公众号的交流群已经建立,许多小伙伴已经加入其中,感谢大家的支持。大家可以在群里交流关于数据分析&数据挖掘的相关内容,还没有加入的小伙伴可以扫描下方管理员二维码,进群前一定要关注公众号奥,关注后让管理员帮忙拉进群,期待大家的加入。
管理员二维码:
猜你喜欢 ● 你相信逛B站也能学编程吗
来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/810/viewspace-3124674/ ,如需转载,请注明出处,否则将追究法律责任。