python3


num = 100
aNum = 1
total = 0
while aNum <= num:
    total = total + aNum
    aNum += 1
# 拼接多个字符串用如下格式
print('1 到 %d 的和为%d -- %s' % (num, total, "hellowlrld"))
# 只拼接一个直接逗号分隔,逗号后面有个空格 即可
print('hhaa', total)

  • 或者如下格式的拼接

  • 或者下面格式不过不建议


print('helloworld' 'amily')

# 结果 helloworldamily

  • 常犯错误字符串与非字符串连接
num_eggs = 12
print('I have ' + num_eggs + ' eggs.')
  • 导致:TypeError: cannot concatenate 'str' and 'int' objects
  • 正确做法:
num_eggs = 12
print('I have ' + str(num_eggs) + ' eggs.')
  • 或者
num_eggs = 12
print('I have %s eggs.' % (num_eggs))

字典的正确打开方式

  • 错误方式
# 在字典对象中访问 key 可以使用 [],但是如果该 key 不存在,就会导致:KeyError: 'zebra'
spam = {'cat': 'Zophie', 'dog': 'Basil', 'mouse': 'Whiskers'}
print('The name of my pet zebra is ' + spam['zebra'])
  • 正确方式应该使用 get 方法:
spam = {'cat': 'Zophie', 'dog': 'Basil', 'mouse': 'Whiskers'}
print('The name of my pet zebra is ' + spam.get('zebra'))
  • key 不存在时,get 默认返回 None
原文地址:https://www.cnblogs.com/adampei-bobo/p/6370239.html