last round of .format conversion for string formatting.

This commit is contained in:
Fletcher Boyd 2013-09-05 10:36:25 +08:00
parent 0aa2185ede
commit 015dd93df3
11 changed files with 45 additions and 45 deletions

View file

@ -63,8 +63,8 @@ def steamcalc(inp, nick='', db=None):
out += soup.findAll('h1', {'class': 'header-title'})[1].text.strip() out += soup.findAll('h1', {'class': 'header-title'})[1].text.strip()
except Exception as e: except Exception as e:
print e print e
return u"\x02Unable to retrieve info for %s!\x02 Is it a valid SteamCommunity profile username (%s)? " \ return u"\x02Unable to retrieve info for {}!\x02 Is it a valid SteamCommunity profile username ({})? " \
"Check if your profile is private, or go here to search: %s" % ( "Check if your profile is private, or go here to search: {}".format(
inp, web.try_isgd("http://steamcommunity.com/id/%s" % inp), web.try_isgd(url)) inp, web.try_isgd("http://steamcommunity.com/id/%s" % inp), web.try_isgd(url))
nextone = False nextone = False
@ -96,8 +96,8 @@ def steamcalc(inp, nick='', db=None):
notplayed = data[2].text.split(" ")[-1] notplayed = data[2].text.split(" ")[-1]
nppercent = data[3].text.split(" ")[-1] nppercent = data[3].text.split(" ")[-1]
time = data[4].text.split(" ")[-1].replace("h", "hours") time = data[4].text.split(" ")[-1].replace("h", "hours")
out += " This account is worth \x02%s\x02, and they've spent \x02%s\x02 playing games! " % (money, time) out += " This account is worth \x02{}\x02, and they've spent \x02{}\x02 playing games! ".format(money, time)
out += " They have \x02%s games\x02, but \x02%s of them haven't been touched\x02! That's \x02%s\x02! " % ( out += " They have \x02{} games\x02, but \x02{} of them haven't been touched\x02! That's \x02{}\x02! ".format(
totalgames, notplayed, nppercent) totalgames, notplayed, nppercent)
if not dontsave: if not dontsave:

View file

@ -27,7 +27,7 @@ def stock(inp):
guess = guess[0]["symbol"] guess = guess[0]["symbol"]
return stock(guess) return stock(guess)
else: else:
return "error: unable to get stock info for '%s'" % inp return "error: unable to get stock info for '{}'".format(inp)
if results['last'] == '0.00': if results['last'] == '0.00':
return "%(company)s - last known stock value was 0.00 %(currency)s" \ return "%(company)s - last known stock value was 0.00 %(currency)s" \

View file

@ -24,9 +24,9 @@ def system(inp):
python_ver = platform.python_version() python_ver = platform.python_version()
architecture = '-'.join(platform.architecture()) architecture = '-'.join(platform.architecture())
cpu = platform.machine() cpu = platform.machine()
return "Hostname: \x02%s\x02, Operating System: \x02%s\x02, Python " \ return "Hostname: \x02{}\x02, Operating System: \x02{}\x02, Python " \
"Version: \x02%s %s\x02, Architecture: \x02%s\x02, CPU: \x02%s" \ "Version: \x02{} {}\x02, Architecture: \x02{}\x02, CPU: \x02{}" \
"\x02" % (hostname, os, python_imp, python_ver, architecture, cpu) "\x02".format(hostname, os, python_imp, python_ver, architecture, cpu)
@hook.command(autohelp=False) @hook.command(autohelp=False)
@ -41,9 +41,9 @@ def memory(inp):
data = [float(i.replace(' kB', '')) for i in data] data = [float(i.replace(' kB', '')) for i in data]
strings = [convert_kilobytes(i) for i in data] strings = [convert_kilobytes(i) for i in data]
# prepare the output # prepare the output
out = "Threads: \x02%s\x02, Real Memory: \x02%s\x02, Allocated Memory: \x02%s\x02, Peak " \ out = "Threads: \x02{}\x02, Real Memory: \x02{}\x02, Allocated Memory: \x02{}\x02, Peak " \
"Allocated Memory: \x02%s\x02, Stack Size: \x02%s\x02, Heap " \ "Allocated Memory: \x02{}\x02, Stack Size: \x02{}\x02, Heap " \
"Size: \x02%s\x02" % (s['Threads'], strings[0], strings[1], strings[2], "Size: \x02{}\x02".format(s['Threads'], strings[0], strings[1], strings[2],
strings[3], strings[4]) strings[3], strings[4])
# return output # return output
return out return out
@ -55,7 +55,7 @@ def memory(inp):
for amount in re.findall(r'([,0-9]+) K', out): for amount in re.findall(r'([,0-9]+) K', out):
memory += float(amount.replace(',', '')) memory += float(amount.replace(',', ''))
memory = convert_kilobytes(memory) memory = convert_kilobytes(memory)
return "Memory Usage: \x02%s\x02" % memory return "Memory Usage: \x02{}\x02".format(memory)
else: else:
return "Sorry, this command is not supported on your OS." return "Sorry, this command is not supported on your OS."
@ -66,10 +66,10 @@ def uptime(inp, bot=None):
"""uptime -- Shows the bot's uptime.""" """uptime -- Shows the bot's uptime."""
uptime_raw = round(time.time() - bot.start_time) uptime_raw = round(time.time() - bot.start_time)
uptime = timedelta(seconds=uptime_raw) uptime = timedelta(seconds=uptime_raw)
return "Uptime: \x02%s\x02" % uptime return "Uptime: \x02{}\x02".format(uptime)
@hook.command(autohelp=False) @hook.command(autohelp=False)
def pid(inp): def pid(inp):
"""pid -- Prints the bot's PID.""" """pid -- Prints the bot's PID."""
return "PID: \x02%s\x02" % os.getpid() return "PID: \x02{}\x02".format(os.getpid())

View file

@ -37,10 +37,10 @@ def tellinput(paraml, input=None, notice=None, db=None, bot=None, nick=None, con
user_from, message, time, chan = tells[0] user_from, message, time, chan = tells[0]
reltime = timesince.timesince(time) reltime = timesince.timesince(time)
reply = "%s sent you a message %s ago from %s: %s" % (user_from, reltime, chan, reply = "{} sent you a message {} ago from {}: {}".format(user_from, reltime, chan,
message) message)
if len(tells) > 1: if len(tells) > 1:
reply += " (+%d more, %sshowtells to view)" % (len(tells) - 1, conn.conf["command_prefix"]) reply += " (+{} more, {}showtells to view)".format(len(tells) - 1, conn.conf["command_prefix"])
db.execute("delete from tell where user_to=lower(?) and message=?", db.execute("delete from tell where user_to=lower(?) and message=?",
(nick, message)) (nick, message))
@ -63,7 +63,7 @@ def showtells(inp, nick='', chan='', notice=None, db=None):
for tell in tells: for tell in tells:
user_from, message, time, chan = tell user_from, message, time, chan = tell
past = timesince.timesince(time) past = timesince.timesince(time)
notice("%s sent you a message %s ago from %s: %s" % (user_from, past, chan, message)) notice("{} sent you a message {} ago from {}: {}".format(user_from, past, chan, message))
db.execute("delete from tell where user_to=lower(?)", db.execute("delete from tell where user_to=lower(?)",
(nick,)) (nick,))
@ -92,7 +92,7 @@ def tell(inp, nick='', chan='', db=None, input=None, notice=None):
if user_to.lower() == input.conn.nick.lower(): if user_to.lower() == input.conn.nick.lower():
# user is looking for us, being a smartass # user is looking for us, being a smartass
notice("Thanks for the message, %s!" % user_from) notice("Thanks for the message, {}!".format(user_from))
return return
if not re.match("^[A-Za-z0-9_|.-\]\[]*$", user_to.lower()): if not re.match("^[A-Za-z0-9_|.-\]\[]*$", user_to.lower()):

View file

@ -9,7 +9,7 @@ api_url = 'http://api.wolframalpha.com/v2/query?format=plaintext'
def time_command(inp, bot=None): def time_command(inp, bot=None):
"""time <area> -- Gets the time in <area>""" """time <area> -- Gets the time in <area>"""
query = "current time in %s" % inp query = "current time in {}".format(inp)
api_key = bot.config.get("api_keys", {}).get("wolframalpha", None) api_key = bot.config.get("api_keys", {}).get("wolframalpha", None)
if not api_key: if not api_key:
@ -27,9 +27,9 @@ def time_command(inp, bot=None):
place = capitalize_first(" ".join(request.xpath("//pod[@" place = capitalize_first(" ".join(request.xpath("//pod[@"
"title='Input interpretation']/subpod/plaintext/text()"))[ "title='Input interpretation']/subpod/plaintext/text()"))[
16:]) 16:])
return "%s - \x02%s\x02" % (time, place) return "{} - \x02{}\x02".format(time, place)
else: else:
return "Could not get the time for '%s'." % inp return "Could not get the time for '{}'.".format(inp)
@hook.command(autohelp=False) @hook.command(autohelp=False)

View file

@ -130,7 +130,7 @@ def todo(inp, nick='', chan='', db=None, notice=None, bot=None):
if not row: if not row:
notice("No such entry.") notice("No such entry.")
return return
notice("[%d]: %s: %s" % (index, row[0], row[1])) notice("[{}]: {}: {}".format(index, row[0], row[1]))
elif cmd == 'del' or cmd == 'delete' or cmd == 'remove': elif cmd == 'del' or cmd == 'delete' or cmd == 'remove':
if not len(args): if not len(args):
return "error" return "error"
@ -146,7 +146,7 @@ def todo(inp, nick='', chan='', db=None, notice=None, bot=None):
rows = db_del(db, nick, index) rows = db_del(db, nick, index)
notice("Deleted %d entries" % rows.rowcount) notice("Deleted {} entries".format(rows.rowcount))
elif cmd == 'list': elif cmd == 'list':
limit = -1 limit = -1
@ -163,11 +163,11 @@ def todo(inp, nick='', chan='', db=None, notice=None, bot=None):
found = False found = False
for (index, row) in enumerate(rows): for (index, row) in enumerate(rows):
notice("[%d]: %s: %s" % (index, row[0], row[1])) notice("[{}]: {}: {}".format(index, row[0], row[1]))
found = True found = True
if not found: if not found:
notice("%s has no entries." % nick) notice("{} has no entries.".format(nick))
elif cmd == 'search': elif cmd == 'search':
if not len(args): if not len(args):
notice("No search query given!") notice("No search query given!")
@ -178,11 +178,11 @@ def todo(inp, nick='', chan='', db=None, notice=None, bot=None):
found = False found = False
for (index, row) in enumerate(rows): for (index, row) in enumerate(rows):
notice("[%d]: %s: %s" % (index, row[0], row[1])) notice("[{}]: {}: {}".format(index, row[0], row[1]))
found = True found = True
if not found: if not found:
notice("%s has no matching entries for: %s" % (nick, query)) notice("{} has no matching entries for: {}".format(nick, query))
else: else:
notice("Unknown command: %s" % cmd) notice("Unknown command: {}".format(cmd))

View file

@ -76,9 +76,9 @@ def get_episode_info(episode, api_key):
if episode_name == "TBA": if episode_name == "TBA":
episode_name = None episode_name = None
episode_desc = '%s' % episode_num episode_desc = '{}'.format(episode_num)
if episode_name: if episode_name:
episode_desc += ' - %s' % episode_name episode_desc += ' - {}'.format(episode_name)
return first_aired, airdate, episode_desc return first_aired, airdate, episode_desc
@ -100,7 +100,7 @@ def tv_next(inp, bot=None):
episodes = episodes["episodes"] episodes = episodes["episodes"]
if ended: if ended:
return "%s has ended." % series_name return "{} has ended.".format(series_name)
next_eps = [] next_eps = []
today = datetime.date.today() today = datetime.date.today()
@ -114,22 +114,22 @@ def tv_next(inp, bot=None):
(first_aired, airdate, episode_desc) = ep_info (first_aired, airdate, episode_desc) = ep_info
if airdate > today: if airdate > today:
next_eps = ['%s (%s)' % (first_aired, episode_desc)] next_eps = ['{} ({})'.format(first_aired, episode_desc)]
elif airdate == today: elif airdate == today:
next_eps = ['Today (%s)' % episode_desc] + next_eps next_eps = ['Today ({})'.format(episode_desc)] + next_eps
else: else:
#we're iterating in reverse order with newest episodes last #we're iterating in reverse order with newest episodes last
#so, as soon as we're past today, break out of loop #so, as soon as we're past today, break out of loop
break break
if not next_eps: if not next_eps:
return "There are no new episodes scheduled for %s." % series_name return "There are no new episodes scheduled for {}.".format(series_name)
if len(next_eps) == 1: if len(next_eps) == 1:
return "The next episode of %s airs %s" % (series_name, next_eps[0]) return "The next episode of {} airs {}".format(series_name, next_eps[0])
else: else:
next_eps = ', '.join(next_eps) next_eps = ', '.join(next_eps)
return "The next episodes of %s: %s" % (series_name, next_eps) return "The next episodes of {}: {}".format(series_name, next_eps)
@hook.command @hook.command
@ -163,11 +163,11 @@ def tv_last(inp, bot=None):
if airdate < today: if airdate < today:
#iterating in reverse order, so the first episode encountered #iterating in reverse order, so the first episode encountered
#before today was the most recently aired #before today was the most recently aired
prev_ep = '%s (%s)' % (first_aired, episode_desc) prev_ep = '{} ({})'.format(first_aired, episode_desc)
break break
if not prev_ep: if not prev_ep:
return "There are no previously aired episodes for %s." % series_name return "There are no previously aired episodes for {}.".format(series_name)
if ended: if ended:
return '%s ended. The last episode aired %s.' % (series_name, prev_ep) return '{} ended. The last episode aired {}.'.format(series_name, prev_ep)
return "The last episode of %s aired %s." % (series_name, prev_ep) return "The last episode of {} aired {}.".format(series_name, prev_ep)

View file

@ -22,5 +22,5 @@ def validate(inp):
if status in ("valid", "invalid"): if status in ("valid", "invalid"):
errorcount = info['x-w3c-validator-errors'] errorcount = info['x-w3c-validator-errors']
warningcount = info['x-w3c-validator-warnings'] warningcount = info['x-w3c-validator-warnings']
return "%s was found to be %s with %s errors and %s warnings." \ return "{} was found to be {} with {} errors and {} warnings." \
" see: %s" % (inp, status, errorcount, warningcount, url) " see: {}".format(inp, status, errorcount, warningcount, url)

View file

@ -37,7 +37,7 @@ def getSoundInfo(url, inp, jsondata=False):
else: else:
text = textsplit[i] text = textsplit[i]
if not jsondata: if not jsondata:
return "%s - %s %s" % (newdata[0]["who"], return "{} - {} {}".format(newdata[0]["who"],
text if len(text) < 325 else text[:325] + "...", text if len(text) < 325 else text[:325] + "...",
web.try_isgd( web.try_isgd(
url + newdata[0]["id"] if not dostream else url + "sound.php?id=" + newdata[0][ url + newdata[0]["id"] if not dostream else url + "sound.php?id=" + newdata[0][

View file

@ -46,4 +46,4 @@ def wiki(inp):
desc = text.truncate_str(desc, 200) desc = text.truncate_str(desc, 200)
return '%s :: %s' % (desc, http.quote(url, ':/')) return '{} :: {}'.format(desc, http.quote(url, ':/'))

View file

@ -54,4 +54,4 @@ def wolframalpha(inp, bot=None):
if not ret: if not ret:
return 'No results.' return 'No results.'
return "%s - %s" % (ret, short_url) return "{} - {}".format(ret, short_url)