【python学习笔记】字符串格式化
# 字符串格式化 ''' {参数序号:格式控制标记} 填充 对齐(< > ^) 宽度 逗号 精度 类型 ''' a = "hello" b = "world" print("{},{}".format(a, b)) print("{1},{0}".format(a, b)) # 填充 s = "hello" print("{0:*^20} world!".format(s)) # 千位逗号 print("{:,}".format(1234567890)) # 精度 print("{:.2f}".format(1234.56789)) print("{:.5}".format("hello, world!")) # 类型 print("{0:b},{0:d},{0:x},{0:X},{0:c}".format(425)) print("{0:c}".format(98))
练习题:
# 统计英文文章中单词出现的频率 wordstring = ''' it was the best of times it was the worst of times. it was the age of wisdom it was the age of foolishness. ''' # 替换标点符号 wordstring = wordstring.replace('.',' ') # 分割单词 wordlist = wordstring.split() print(wordlist) # 统计次数 wordfreq = [] for w in wordlist: wordfreq.append(wordlist.count(w)) # append函数返回None # 字典格式输出单词出现的频率 f = dict(zip(wordlist, wordfreq)) print(f)
# 字符串格式化 s = 'python' print("{0:3}".format(s)) # 参数序号,格式控制符 # 长字符串 print(''' 唐诗\n 宋词 ''') # 原始字符串 print(r''' 唐诗\n 宋词 ''')