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.
刚开始运营的微信公众号,欢迎拍砖,欢迎交流~~

请使用浏览器的分享功能分享到微信等