本文整理汇总了Python中string.join函数的典型用法代码示例。如果您正苦于以下问题:Python join函数的具体用法?Python join怎么用?Python join使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了join函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的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
示例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), ".")))
示例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, ',')
示例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
示例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, ", ")
示例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)
示例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)), "")
示例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)
示例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
示例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
示例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"))
示例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")
示例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, ','))
示例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);
示例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