Python 字符串之冷饭新样

1.for重新实现:1+2+3…+100=?

运行结果:

Python代码:

点击(此处)折叠或打开

  1. #use for to compute 1+2+3+...+100
  2. final=0
  3. for i in range(1,101):
  4.     final=final+i
  5. print '1+2+3+...+100 =',final

释义:

         range(1, 101)表示从1开始,到101为止(不包括101),取其中所有的整数。

         相比昨天的while,这里不再需要一个单独变量记录循环的次数。

--*--*--*--*--*--*--*--*--*--*--*--*--*--*--*--*--*--*--*--*--*--*--*--*--*--*--*--*--*--*--*--*--*--*--*--

2. 字符串格式化输出

运行结果:


代码:

点击(此处)折叠或打开

  1. from random import randint
  2. num=randint(1,100)
  3. print 'Guess what I think?'
  4. final=False
  5.  
  6. while final==False:
  7.     answer=input()
  8.  
  9.     if answer<num:
  10.         print '%d is too small!'%answer
  11.     if answer>num:
  12.         print str(answer)+' is too big!'
  13.     if answer==num:
  14.         print "Good, you guess it! It's %d."%answer
  15.         final=True

两种格式化方法:

1)  str():把数字转换成字符串

2)  用%对字符串进行格式化:

%d替换整数;

%f替换小数(想保留两位小数, %.2f);

%s来替换一段字符串

--*--*--*--*--*--*--*--*--*--*--*--*--*--*--*--*--*--*--*--*--*--*--*--*--*--*--*--*--*--*--*--*--*--*--*--

补个基础知识:字符串的用法

运行结果:


代码:


点击(此处)折叠或打开

  1. print 'Method 1;',"Yiyi's mom."
  2. print 'Method 1:','Yiyi is a "good" baby.'
  3. print 'Method 2:','''"What's your name?" "I'm Yiyi."'''
  4. print 'Method 2:', """"And you?" "I'm Iris." """
  5. print 'Method 3:','I\'m a \"good\" baby.'
  6. print 'Method 3:','This is \
  7. same line.'


知识点:

  最常用的字符串表示方式是单引号(‘’)和双引号(“”):’string’和”string”效果一样

  一定必须得是英文字符!

  输出中本身有单双引号,咋办?见上栗,能看出有3种方法不?

Question: ‘\n’用来做什么呢?


点击(此处)折叠或打开

  1. print 'Well study,\nwell think,\nwell listen,\n\
  2. well do,\nwell speak\n --come on!'
  3. print '^_^ @_@ *_* '


结果:

程序运行版本

Python 2.7.13 (v2.7.13:a06454b1afa1, Dec 17 2016, 20:53:40) [MSC v.1500 64 bit (AMD64)] on win32

Type "copyright", "credits" or "license()" for more information.
刚开始运营的微信公众号,欢迎拍砖,欢迎交流~~

来自 “ ITPUB博客 ” ,链接:http://blog.itpub.net/26129555/viewspace-2142637/,如需转载,请注明出处,否则将追究法律责任。

转载于:http://blog.itpub.net/26129555/viewspace-2142637/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值