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

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

没有评论:

发表评论