千家信息网

如何进行Python 字符串分析

发表于:2024-10-04 作者:千家信息网编辑
千家信息网最后更新 2024年10月04日,今天就跟大家聊聊有关如何进行Python 字符串分析,可能很多人都不太了解,为了让大家更加了解,小编给大家总结了以下内容,希望大家根据这篇文章可以有所收获。1.for重新实现:1+2+3…+100=?
千家信息网最后更新 2024年10月04日如何进行Python 字符串分析

今天就跟大家聊聊有关如何进行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. while final==False:

  6. answer=input()


  7. if answer

  8. print '%d is too small!'%answer

  9. if answer>num:

  10. print str(answer)+' is too big!'

  11. if answer==num:

  12. print "Good, you guess it! It's %d."%answer

  13. 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.

看完上述内容,你们对如何进行Python 字符串分析有进一步的了解吗?如果还想了解更多知识或者相关内容,请关注行业资讯频道,感谢大家的支持。

0