本文整理汇总了Python中string.join函数的典型用法代码示例。如果您正苦于以下问题:Python join函数的具体用法?Python join怎么用?Python join使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了join函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。
示例1: _writeLifecycle
def _writeLifecycle(self, fileOut):
"""
Write default constructor and destructor.
"""
# Constructor
fileOut.write("%s::%s::%s(void)\n" % \
(string.join(self.namespace, "::"),
self.objname, self.objname))
fileOut.write("{ // constructor\n")
for scalar in self.scalars:
n = scalar['name']
if "char*" != scalar['type']:
fileOut.write(" %s = %s;\n" % (n[1:], n))
else:
fileOut.write(" %s = const_cast<char*>(%s);\n" % (n[1:], n))
for array in self.arrays:
n = array['name']
fileOut.write(" %s = const_cast<%s*>(%s);\n" % \
(n[1:], array['type'], n))
fileOut.write("} // constructor\n\n")
# Destructor
fileOut.write("%s::%s::~%s(void)\n" % \
(string.join(self.namespace, "::"),
self.objname, self.objname))
fileOut.write("{}\n\n")
return
开发者ID:jjle,项目名称:pylith,代码行数:29,代码来源:CppData.py
示例2: checkVersion
def checkVersion():
import sys, string
if sys.version_info < requiredPythonVersion:
raise Exception("%s requires at least Python %s, found %s instead." % (
name,
string.join(map(str, requiredPythonVersion), "."),
string.join(map(str, sys.version_info), ".")))
开发者ID:eaudeweb,项目名称:naaya,代码行数:7,代码来源:__init__.py
示例3: _format_data
def _format_data(self, start_time, timestamp, name, units, values):
fields = _fields[:]
file_timestamp = time.strftime('%Y%m%d%H%M',time.gmtime(start_time))
value_timestamp = time.strftime('%Y%m%d%H%M',time.gmtime(timestamp))
fields[_field_index['units']] = units
fields[_field_index['commodity']] = self.commodity
meter_id = name + '|1'
if units:
meter_id += '/%s' % units
fields[_field_index['meter_id']] = meter_id
fields[_field_index['receiver_id']] = ''
fields[_field_index['receiver_customer_id']] = self.customer_name + '|' + self.account_name
fields[_field_index['timestamp']] = file_timestamp
# interval put into "MMDDHHMM" with MMDD = 0000
fields[_field_index['interval']] = '0000%02d%02d' % (self.period / 3600, (self.period % 3600) / 60)
fields[_field_index['count']] = str(len(values))
value_sets = []
for value in values:
try:
value = '%f' % value
protocol_text = ''
except ValueError:
value = ''
protocol_text = 'N'
value_set = (value_timestamp, protocol_text, value)
value_sets.append(string.join(value_set, ','))
value_timestamp = ''
fields[_field_index['interval_data']] = string.join(value_sets, ',')
return string.join(fields, ',')
开发者ID:mcruse,项目名称:monotone,代码行数:29,代码来源:cmep_formatter.py
示例4: makePWCSV
def makePWCSV(pathwayconnections):
curStr = '"Pathway1 KEGG","Pathway2 KEGG","Connecting reactions","Connection metabolites"\n'
for pathway in sorted(pathwayconnections.keys()):
cPathways = pathwayconnections[pathway]
#print pathway
for cPathway in cPathways:
if cPathway[:5] != "path:":
ctPathway = "path:" + cPathway
else:
ctPathway = cPathway
cReactionsStr = ""
cMeabolitesStr = ""
if pathway[:5] != "path:":
tPathway = "path:" + pathway
else:
tPathway = pathway
if ((tPathway in pathwayReact.keys()) and (ctPathway in pathwayReact.keys())):
cReactions = [reaction[3:] for reaction in pathwayReact[tPathway] if reaction in pathwayReact[ctPathway]]
cReactionsStr = string.join(cReactions,"|")
cMetabolites = []
for reaction in cReactions:
tReaction = "rn:" + reaction
if tReaction in reactionsD.keys():
for metabolite in reactionsD[tReaction]["METABOLITES"]:
if metabolite not in cMetabolites:
cMetabolites.append(metabolite)
cMetabolitesStr = string.join(cMetabolites,"|")
#[metabolite for metabolite in rDictionary[reaction]["METABOLITES"] if metaolite in cReactions]
curStr+= '"%s","%s","%s","%s"\n' % (pathway[5:], cPathway,cReactionsStr,cMetabolitesStr)
return curStr
开发者ID:isanwong,项目名称:KEGG-Crawler,代码行数:35,代码来源:crawler.py
示例5: join_header_words
def join_header_words(lists):
"""Do the inverse of the conversion done by split_header_words.
Takes a list of lists of (key, value) pairs and produces a single header
value. Attribute values are quoted if needed.
>>> join_header_words([[("text/plain", None), ("charset", "iso-8859/1")]])
'text/plain; charset="iso-8859/1"'
>>> join_header_words([[("text/plain", None)], [("charset", "iso-8859/1")]])
'text/plain, charset="iso-8859/1"'
"""
headers = []
for pairs in lists:
attr = []
for k, v in pairs:
if v is not None:
if not re.search(r"^\w+$", v):
v = join_escape_re.sub(r"\\\1", v) # escape " and \
v = '"%s"' % v
if k is None: # Netscape cookies may have no name
k = v
else:
k = "%s=%s" % (k, v)
attr.append(k)
if attr: headers.append(string.join(attr, "; "))
return string.join(headers, ", ")
开发者ID:wpjunior,项目名称:proled,代码行数:27,代码来源:_HeadersUtil.py
示例6: UpdateIcon
def UpdateIcon(self, force=False, info=None):
try:
isOnline = self.connection.IsOnline(force)
except UpdateStatusException:
return
if isOnline:
status = u"在线"
icon = 'online'
else:
status = u"离线"
icon = 'offline'
if info == None:
tooltip = string.join(("pNJU", status), " - ")
else:
tooltip = string.join(("pNJU", status, info), " - ")
self.SetIcon(self.MakeIcon(icon), tooltip)
if force and isOnline:
newVersion = self.connection.CheckNewVersion()
if newVersion is not None:
confirm = wx.MessageBox(
u"发现新版本:{0}。是否立即查看更新信息?".format(newVersion),
u"pNJU 发现新版本",
wx.YES_NO | wx.YES_DEFAULT
)
if confirm == wx.YES:
import webbrowser
webbrowser.open(config.WEBSITE)
开发者ID:rdgt321,项目名称:p-NJU,代码行数:31,代码来源:ui.py
示例7: create_columns
def create_columns(self, table_id):
"""
Create the columns for the table in question. We call fix_datatype to
clean up anything PGSQL or MYSQL specific. The function is to be
overidden by the database-specific subclass in question.
"""
col_list = self.tables[table_id].get_columns()
table_name = self.tables[table_id].name
num_cols = len(col_list)
if verbose:
print "Found %s columns" % num_cols
for index in range(num_cols):
colname = col_list[index]
coltype = self.tables[table_id].get_col_type(colname)
coltype = self.fix_datatype(coltype)
colvalue = self.tables[table_id].get_col_value(colname)
colcomm = self.tables[table_id].get_col_comm(colname)
if colcomm:
colcomm.strip()
self.sql_create = string.join((self.sql_create, "\n\t/* ", \
colcomm, " */"), "")
col_statement = self.fix_value(table_name, colname, coltype, colvalue)
if index < num_cols-1:
self.sql_create = string.join((self.sql_create, "\n\t", \
string.upper(col_statement)+","), "")
else:
self.sql_create = string.join((self.sql_create, "\n\t", \
string.upper(col_statement)), "")
开发者ID:AnarKyx01,项目名称:scorebot,代码行数:31,代码来源:dia2sql.py
示例8: readKit
def readKit(self, parent):
"""
Reads the data from a xml file (auxiliar recursive function).
"""
for node in parent.childNodes:
if node.nodeType == Node.ELEMENT_NODE:
attrs = node.attributes
for attrName in attrs.keys():
attrNode = attrs.get(attrName)
attrValue = attrNode.nodeValue
self._Kit[attrName] = attrValue
content = []
for child in node.childNodes:
if child.nodeType == Node.TEXT_NODE:
content.append(child.nodeValue)
if content and (node.nodeName != "control" and node.nodeName != "kitPackage"):
strContent = string.join(content)
tmpContent = strContent.replace("\n ", "")
self._Kit[node.nodeName] = tmpContent.replace("\n ", "")
if content and node.nodeName == "kitPackage":
strContent = string.join(content)
tmpContent = strContent.replace("\n ", "")
self._kitPackages.append(tmpContent.replace("\n ", ""))
self.readKit(node)
开发者ID:pcabido,项目名称:aptkit,代码行数:27,代码来源:xmlutil.py
示例9: compact_traceback
def compact_traceback ():
t,v,tb = sys.exc_info()
tbinfo = []
if tb is None:
# this should never happen, but then again, lots of things
# should never happen but do.
return (('','',''), str(t), str(v), 'traceback is None!!!')
while 1:
tbinfo.append (
tb.tb_frame.f_code.co_filename,
tb.tb_frame.f_code.co_name,
str(tb.tb_lineno)
)
tb = tb.tb_next
if not tb:
break
# just to be safe
del tb
file, function, line = tbinfo[-1]
info = '[' + string.join (
map (
lambda x: string.join (x, '|'),
tbinfo
),
'] ['
) + ']'
return (file, function, line), str(t), str(v), info
开发者ID:0omega,项目名称:platform_external_clearsilver,代码行数:30,代码来源:who_calls.py
示例10: gettags
def gettags(comment):
tags = []
tag = None
tag_lineno = lineno = 0
tag_text = []
for line in comment:
if line[:1] == "@":
tags.append((tag_lineno, tag, string.join(tag_text, "\n")))
line = string.split(line, " ", 1)
tag = line[0][1:]
if len(line) > 1:
tag_text = [line[1]]
else:
tag_text = []
tag_lineno = lineno
else:
tag_text.append(line)
lineno = lineno + 1
tags.append((tag_lineno, tag, string.join(tag_text, "\n")))
return tags
开发者ID:nfac,项目名称:experimental-qt,代码行数:25,代码来源:pythondoc.py
示例11: Table
def Table(self, t,
has_head=1, headcolor="#ffc0c0", bgcolor="#ffffff"):
if has_head:
head = []
for th in t.pop(0):
head.append("<th><font size=\"-1\" face=\"arial,sans-serif\">"
"%s</font></th>" % th)
# endfor
table = ["<tr bgcolor=\"%s\">\n%s</th>\n" % (
headcolor, string.join(head, "\n"))]
else:
table = []
# endif
for tr in t:
row = []
for td in tr:
row.append("<td><font size=\"-1\" face=\"arial,sans-serif\">"
"%s</font></td>" % td)
# endfor
table.append("<tr bgcolor=\"%s\">\n%s</th>\n" % (
bgcolor, string.join(row, "\n")))
# endfor
return "<p><table cellpadding=5 width=100%%>\n%s\n</table></p>\n" % (
string.join(table, "\n"))
开发者ID:JFoulds,项目名称:BHWGoogleProject,代码行数:25,代码来源:autorunner.py
示例12: toXML
def toXML(self, writer, ttFont):
if hasattr (ttFont, "disassembleInstructions") and ttFont.disassembleInstructions:
assembly = self.getAssembly()
writer.begintag("assembly")
writer.newline()
i = 0
nInstr = len(assembly)
while i < nInstr:
instr = assembly[i]
writer.write(instr)
writer.newline()
m = _pushCountPat.match(instr)
i = i + 1
if m:
nValues = int(m.group(1))
line = []
j = 0
for j in range(nValues):
if j and not (j % 25):
writer.write(string.join(line, " "))
writer.newline()
line = []
line.append(assembly[i+j])
writer.write(string.join(line, " "))
writer.newline()
i = i + j + 1
writer.endtag("assembly")
else:
writer.begintag("bytecode")
writer.newline()
writer.dumphex(self.getBytecode())
writer.endtag("bytecode")
开发者ID:kipulcha,项目名称:fonttools,代码行数:32,代码来源:ttProgram.py
示例13: build_post_policy
def build_post_policy(self, expiration_time, conditions):
if type(expiration_time) != time.struct_time:
raise 'Policy document must include a valid expiration Time object'
if type(conditions) != types.DictionaryType:
raise 'Policy document must include a valid conditions Hash object'
# Convert conditions object mappings to condition statements
conds = []
for name in conditions:
test = conditions[name]
if not test:
# A nil condition value means allow anything.
conds.append('["starts-with", "$%s", ""]' % name)
elif type(test) == types.StringType:
conds.append('{"%s": "%s"}' % (name, test))
elif type(test) == types.ListType:
conds.append('{"%s": "%s"}' % (name, string.join(test, ',')))
elif type(test) == types.DictionaryType:
operation = test['op']
value = test['value']
conds.append('["%s", "$%s", "%s"]' % (operation, name, value))
elif type(test) == types.SliceType:
conds.append('["%s", %i, %i]' % (name, test.start, test.stop))
else:
raise 'Unexpected value type for condition "%s": %s' % \
(name, type(test))
return '{"expiration": "%s",\n"conditions": [%s]}' % \
(time.strftime(self.ISO8601, expiration), string.join(conds, ','))
开发者ID:obulpathi,项目名称:aws,代码行数:30,代码来源:S3.py
示例14: MoveFolder
def MoveFolder(self, From, To):
OPList = SymbolTools.SplitPath(From);
OName = OPList[-1];
SPList = OPList[:-1];
Src = "/"+string.join(SPList,"/");
NPList = SymbolTools.SplitPath(To);
NName = NPList[-1];
DPList = NPList[:-1];
Dest = "/"+string.join(DPList,"/");
#check if source exists:
if not self.CheckFolder(From):
raise Exceptions.ItemNotFound("Can't move folder %s to %s: source doesn't exists!"%(From,To));
#check if destination is a symbol:
if self.CheckSymbol(To):
raise Exceptions.SymbolError("Can't move folder %s to %s: destination allready exists!"%(From,To));
#remove folder from source:
folder_obj = self.__GetElementByPath(OPList);
src_obj = self.__GetElementByPath(SPList);
src_obj.RemoveFolder(OName);
#check if dest-folder isn't in src-folder:
if not self.CheckFolder(Dest):
src_obj.AddFolder(OName, folder_obj);
raise Exceptions.SymbolError("Can't move folder %s to %s: destination is part of the source!"%(From,To));
#move folder
dest_obj = self.__GetElementByPath(DPList);
folder_obj.Rename(NName);
dest_obj.AddFolder(NName, folder_obj);
开发者ID:BackupTheBerlios,项目名称:pplt-svn,代码行数:29,代码来源:SymbolTree.py
示例15: main
def main():
t1 = clock()
filename = "HashInt.txt"
inputfile = open(filename, 'r')
numberDict = dict()
for line in inputfile:
number = eval(line)
if not (number in numberDict):
numberDict[number] = None
inputfile.close()
resultList = [None] * 9
testfile = open("test.txt", 'r')
index = 0
for line in testfile:
dest = eval(line)
for number in numberDict.keys():
if (dest - number) in numberDict:
resultList[index] = '1'
break
if resultList[index] == None:
resultList[index] = '0'
index = index + 1
print join(resultList, "")
testfile.close()
print clock() - t1
开发者ID:xiayan,项目名称:Coursera_classes,代码行数:26,代码来源:twosum.py
示例16: PrintRecords
def PrintRecords(labels, s4, fmtHead, fmtTail="", printHex=True, printNorm=True):
fmt = fmtHead
szHead = struct.calcsize(fmtHead)
szTail = struct.calcsize(fmtTail)
printableHead = string.join([x for x in fmtHead if fmtmap.has_key(x)],"")
printableTail = string.join([x for x in fmtTail if fmtmap.has_key(x)],"")
if fmtTail != "":
gap = len(s4[0]) - (struct.calcsize(fmtHead) + struct.calcsize(fmtTail))
fmt = fmtHead + ("x"*gap) + fmtTail
labels = ["LINE"] + labels[:len(printableHead)] + labels[len(labels)-len(printableTail):]
PrintMultiLineLabels(labels,6)
sys.stdout.write(6*" ")
PrintByteLabels(fmt, len(s4))
for i in range(0, len(s4)):
if printNorm:
sys.stdout.write("%5i:%s\n" % (i, StructToString(s4[i], fmt, 6)))
if printHex:
sys.stdout.write("\33[0m")
sys.stdout.write(" %s\n" % (StructToString(s4[i], fmt, 6, color=False, hexonly=True)))
if not ((i+1) % 40) or (i == len(s4) - 1):
PrintMultiLineLabels(labels,6)
sys.stdout.write(6*" ")
PrintByteLabels(fmt, len(s4))
#HexPrintMod(s4[i][:szHead].tostring() + s4[i][len(s4[i]) - szTail:].tostring(), szHead + szTail)
PrintByteStats(s4, fmt)
开发者ID:greenthrall,项目名称:BB_Sync_Test,代码行数:25,代码来源:BodyBugg.py
示例17: getBulletin
def getBulletin(self, includeError=False, useFinalLineSeparator=True):
"""getBulletin([includeError]) -> bulletin
bulletin : String
includeError: Bool
- If True, include error in bulletin body.
useFinalLineSeparator: Bool
- If True, use finalLineSeparator
returns the bulletin text.
"""
if useFinalLineSeparator:
marqueur = self.finalLineSeparator
else:
marqueur = self.lineSeparator
if self.errorBulletin == None:
return string.join(self.bulletin, marqueur)
else:
if includeError:
return ("### " + self.errorBulletin[0] + marqueur + "PROBLEM BULLETIN" + marqueur) + string.join(
self.bulletin, marqueur
)
else:
return string.join(self.bulletin, marqueur)
开发者ID:khosrow,项目名称:metpx,代码行数:28,代码来源:bulletin.py
示例18: generate
def generate(tmpl, name, table):
w_arg_names = [a[1] for a in table[name] if a[0] == 'fop-arg']
w_arg_types = [a[2] for a in table[name] if a[0] == 'fop-arg']
u_arg_names = [a[1] for a in table[name] if a[0] == 'cbk-arg']
u_arg_types = [a[2] for a in table[name] if a[0] == 'cbk-arg']
fn_arg_names = [a[1] for a in table[name] if a[0] == 'fn-arg']
fn_arg_types = [a[2] for a in table[name] if a[0] == 'fn-arg']
ret_type = [a[1] for a in table[name] if a[0] == 'ret-val']
ret_var = [a[2] for a in table[name] if a[0] == 'ret-val']
sdict = {}
#Parameters are (t1, var1), (t2, var2)...
#Args are (var1, var2,...)
sdict["@[email protected]"] = string.join(w_arg_names, ", ")
sdict["@[email protected]"] = string.join(u_arg_names, ", ")
sdict["@[email protected]"] = string.join(map(get_error_arg, u_arg_types), ", ")
sdict["@[email protected]"] = get_param(w_arg_names, w_arg_types)
sdict["@[email protected]"] = get_param(u_arg_names, u_arg_types)
sdict["@[email protected]"] = get_param(fn_arg_names, fn_arg_types)
sdict["@[email protected]"] = name
sdict["@[email protected]"] = fop_prefix
sdict["@[email protected]"] = string.join(ret_type, "")
sdict["@[email protected]"] = string.join(ret_var, "")
for old, new in sdict.iteritems():
tmpl = tmpl.replace(old, new)
# TBD: reindent/reformat the result for maximum readability.
return tmpl
开发者ID:Muthu-vigneshwaran,项目名称:glusterfs,代码行数:28,代码来源:generate_xlator.py
示例19: parse_quoted_string
def parse_quoted_string(self, unfold=False):
"""Parses a quoted-string.
Parses a single instance of the production quoted-string. The
return value is the entire matching string (including the quotes
and any quoted pairs) or None if no quoted-string was found.
If *unfold* is True then any folding LWS is replaced with a
single SP. It defaults to False"""
if not self.parse(DQUOTE):
return None
qs = [DQUOTE]
while self.the_char is not None:
if self.parse(DQUOTE):
qs.append(DQUOTE)
break
elif self.match("\\"):
qp = self.parse_quoted_pair()
if qp:
qs.append(qp)
else:
raise ValueError(
"Expected quoted pair: %s..." % self.peek(5))
else:
qdtext = self.parse_qdtext(unfold)
if qdtext:
qs.append(qdtext)
else:
raise BadSyntax("Expected closing <\">: %s%s..." %
(string.join(qs, ''), self.peek(5)))
return string.join(qs, '')
开发者ID:araymund,项目名称:pyslet,代码行数:31,代码来源:grammar.py
示例20: extract_key
def extract_key( self ):
text = string.strip( self.text )
key = string.join( string.split( text ) )
words = string.split( key )
key = string.join( words[ :2 ] )
self.text = ''
try:
self.open_tag = self.open_tag_stack.pop()
except:
self.open_tag = 'open_html'
if( self.open_tag == 'open_table_data' ):
if( self.context == 'general_info' ):
if( self.key_waiting == '' ):
self.key_waiting = key
self.text = ''
elif( self.context == 'seq_info' ):
if( text == 'Key to Symbols' ):
self.context = 'legend'
self.master_key = key
elif( self.context == 'general_info' ):
self.master_key = key
if( string.find( key, 'SEQUENCE' ) != -1 ):
self.context = 'seq_info'
self.queue[ key ] = UserDict.UserDict()
elif( self.context == 'seq_info' ):
self.queue[ key ] = UserDict.UserDict()
self.master_key = key
开发者ID:BingW,项目名称:biopython,代码行数:28,代码来源:UniGene.py
注:本文中的string.join函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论