显示标签为“Python”的博文。显示所有博文
显示标签为“Python”的博文。显示所有博文

2009年2月16日星期一

Python查找并替换字符串

Python字符串提供了replace(old,new,maxreplace)方法,用新的文本替换指定的子字符串。replace方法接收一个查找字符串作为第一个参数,替换字符串作为第二参数。每一个查找到的字符串都将用一个新的字符串替换掉。作为可选,你可以指定一个最大的执行替换操作次数的数字作为第三个参数。

question = "What is the air speed velocity of \
an unlaiden swallow?"
print question
question2 = question.replace("swallow", \
"European swallow")
print question2
question3 = question.replace("swallow", \
"African swallow")
print question3

replace_str.py

What is the air speed velocity of an unlaiden
swallow?
What is the air speed velocity of an unlaiden
European swallow?
What is the air speed velocity of an unlaiden
African swallow?

Output from replace_str.py code

原文:<< Python Phrasebook: Essential Code and Commands>> Search and Replace in Strings

[声明]:限于译者水平,文中难免错漏之处,欢迎各位网友批评指正;

Python查找子字符串

Python提供find(sub, [, start, [,end]]))和index(sub, [, start, [,end]])这两种最常见的方法查找字符串中的子字符串。

index方法的查找速度比find快;然而,如果在字符串中没有找到所需的子字符串,index方法将抛出一个异常。如果find没有找到所需的子字符串,那么它将返回-1。find和index方法接受要查询的字符串作为它的第一个参数。被查找的字符串范围可以通过具体指定可选的开始和/或结束索引限制。只有在这索引之间的字符才会被查找。

Python也提供了rfind和rindex方法。这两个方法的工作方式和find和index很像。然而,它们是从字符串的右边开始查找子字符串。

searchStr =
"Red Blue Violet Green Blue Yellow Black"

print searchStr.find("Red")
print searchStr.rfind("Blue")
print searchStr.find("Blue")
print searchStr.find("Teal")
print searchStr.index("Blue")
print searchStr.index("Blue",20)
print searchStr.rindex("Blue")
print searchStr.rindex("Blue",1,18)

search_str.py

0
22
4
-1
4
22
22
4

Output from search_str.py code

原文:<< Python Phrasebook: Essential Code and Commands>> Searching Strings for Substrings

[声明]:限于译者水平,文中难免错漏之处,欢迎各位网友批评指正;

2009年2月15日星期日

Python拆分字符串

Python提供split(separator)和splitlines(keeplineeds)方法用于拆分字符串。split方法查找字符串,并根据分隔符拆分,把拆分好的子字符串放入字符串列表中。如果没有具体指定分隔符,split方法将使用空格来拆分。

splitlines方法根据换行符拆分字符串,并把结果放入字符串列表。当你解析很大文本的时候这将是很有用的。splitlines方法接收一个布尔型的参数决定换行符是否被保留。

sentence = "A Simple Sentence."

paragraph = "This is a simple paragraph.\n\
It is made up of of multiple\n\
lines of text."

entry =
"Name:Brad Dayley:Occupation:Software Engineer"

print sentence.split()
print entry.split(':')
print paragraph.splitlines(1)

split_str.py

['A', 'Simple', 'Sentence.']
['Name', 'Brad Dayley', 'Occupation',
'Software Engineer']
['This is a simple paragraph.\n',
'It is made up of of multiple\n',
'lines of text.']

Output from split_str.py code

原文:<< Python Phrasebook: Essential Code and Commands>> Splitting Strings

[声明]:限于译者水平,文中难免错漏之处,欢迎各位网友批评指正;

Python连接字符串

在Python中可以使用简单的加法操作,格式化字符串连接或者join()方法来连接字符串。使用+或+=是比较简单的实现连接方式。

格式化字符串连接是通过定义一个带有格式化代码%s的新字符串来实现,并使用额外的字符串作为参数去填充每个字符串格式化代码。这个可能非常有用,特别当要连接一个复杂格式的字符串时。

连接一个字符串列表的最快方式是使用join(wordList)方法,在列表中的每个字符串将被连接在一起。join方法有一点点的特别因为它本质是迭代字符串列表并执行string+=list[x]操作。这样的结果是字符串将被增加到每个列表元素的前面。如果你想在列表中的词之间增加一个空格这个将变得非常有用,因为你只要简单地定义一个包含一个空格的字符串并实现join方法就可以了:

word1 = "A"
word2 = "few"
word3 = "good"
word4 = "words"
wordList = ["A", "few", "more", "good", "words"]

#simple Join
print "Words:" + word1 + word2 + word3 + word4
print "List: " + ' '.join(wordList)

#Formatted String
sentence = ("First: %s %s %s %s." %
(word1,word2,word3,word4))
print sentence

#Joining a list of words
sentence = "Second:"
for word in wordList:
sentence += " " + word
sentence += "."
print sentence

join_str.py

Words:Afewgoodwords
List: A few more good words
First: A few good words.
Second: A few more good words.

Output from join_str.py code

原文:<<Python Phrasebook: Essential Code and Commands> >Joining Strings

[声明]:限于译者水平,文中难免错漏之处,欢迎各位网友批评指正;

2009年2月14日星期六

Python比较字符串

在Python中比较字符串最好是使用简单逻辑操作符。例如,确定一个字符串是否和另外一个字符串匹配。正确的,你可以使用is equal或==操作符。你也可以使用例如>=或<来确定几个字符串的排列顺序。

Python字符串对象提供了几个方法用来帮助字符串比较。最经常使用的是upper()和lower()方法,它们将分别返回一个新的小写字母字符串和新的大写字母字符串。

另外一个有用的方法是capitalize(),它返回一个第一个字母是大写的新字符串。还有一个swapcase()方法,返回一个新的字符串,并且每个字符的大小写刚好跟原来相反。

cmpStr = "abc"
upperStr = "ABC"
lowerStr = "abc"

print "Case Sensitive Compare"
if cmpStr == lowerStr:
print lowerStr + " Matches " + cmpStr

if cmpStr == upperStr:
print upperStr + " Matches " + cmpStr

print "\nCase In-Sensitive Compare"
if cmpStr.upper() == lowerStr.upper():
print lowerStr + " Matches " + cmpStr

if cmpStr.upper() == upperStr.upper():
print upperStr + " Matches " + cmpStr

comp_str.py

Case Sensitive Compare
abc Matches abc

Case In-Sensitive Compare
abc Matches abc
ABC Matches abc

Output from comp_str.py code

原文:<<Python Phrasebook: Essential Code and Commands>> 2.1

限于译者水平,文中难免错漏之处,欢迎各位网友批评指正;

2009年2月10日星期二

2009年2月4日星期三

Python介绍和概述

Python现在是最流行的动态编程语言之一,紧接着是Perl,Tcl,PHP和最近的Ruby。虽然它经常被看做是“脚本语言”,但实际上它是和List或者Smalltalk类似写法的通用编程语言。今天,python被用在很多地方,从使用完就扔的脚本到提供24x7不间断服务的大型web服务。它还用在GUI和数据库编程,客户端和服务端web编程,程序测试。科学家还使用它为世界上最快的计算机编写应用程序并且是小孩子友好的初学语言。

在这个博客中,我将聚焦Python的历史。特别,Python是如何开发,在它的设计中主要的影响,造成的错误,经验学习和这个语言将来的趋势。

感谢:这个博客中很多好的语句都受惠于Dave Beazley(更多关于这个博客的由来,看我另外一个博客)。

鸟瞰Python

当人们第一次接触Python,他们经常是对Python的代码印象深刻,至少在表面上,Python的代码和传统的编程语言如C或者Pascal是很相似的。这不是偶然,Python的语法大量借鉴了C语言。例如,很多的Python关键子和C语言是一样的(if,else,while,for,等等...),Python标识符的命名规则和C是一样的。当然了,Python不是C,一个很大的区别是Python使用缩进代替C语言的中括号。例如,C语言像这样:

if (a < max =" b;" max =" a;" max =" b" max =" a" regex =" re.compile(r'href="" max="10):" data =" urllib.urlopen(url).read()" hits =" regex.findall(data)" href="http://python-history.blogspot.com/2009/01/introduction-and-overview.html">Introduction and Overview

[声明]:限于译者水平,文中难免错漏之处,欢迎各位网友批评指正;