Some python print

HOW TO Make Terminal Beautiful In Python

1.ColorFul Print

Demo1:

print("\033[1;31;40mhello world\033[0m")  #red 
print("\033[1;31;43mhello world\033[0m")  #frontground:red ,background:yello
print("\033[0;31m%s\033[0m" % "bbbbbbbb")

print('This is a \033[1;35m test \033[0m!')
print('This is a \033[1;32;43m test \033[0m!')
print('\033[1;33;44mThis is a test !\033[0m')


s="hello world"
t='hello'
print s.replace(t,'\033[1;31;40m%s\033[0m'%(t))

format: like :[\33[91m + info + \33[0m]

Demo2: colorful logging tools
class Logger:                                                                      
        HEADER = '\033[95m'                                                        
        OKBLUE = '\033[94m'                                                        
        OKGREEN = '\033[92m'                                                       
        WARNING = '\033[93m'                                                       
        FAIL = '\033[91m'                                                          
        ENDC = '\033[0m'                                                           

        @staticmethod                                                              
        def log_normal(info):                                                      
                print Logger.OKBLUE + info + Logger.ENDC                           

        @staticmethod                                                              
        def log_high(info):                                                        
                print Logger.OKGREEN + info + Logger.ENDC                          

        @staticmethod                                                              
        def log_fail(info):                                                        
                print Logger.FAIL + info + Logger.ENDC    

if __name__ =='__main__':
Logger.log_normal("This is a normal message!")
Logger.log_fail("This is a fail message!")
Logger.log_high("This is a high-light message!")

Attribute Info

--------------------------------------以Linux的ansi终端为例----------------------------------
\33[0m 关闭所有属性 
\33[1m 设置高亮度 
\33[4m 下划线 
\33[5m 闪烁 
\33[7m 反显 
\33[8m 消隐 
\33[30m -- \33[37m 设置前景色
字颜色:30-----------37 
30:黑 
31:红 
32:绿 
33:黄 
34:蓝色 
35:紫色 
36:深绿
37:白色 

\33[40m -- \33[47m 设置背景色 
字背景颜色范围:40----47 
40:黑 
41:深红 
42:绿 
43:黄色 
44:蓝色 
45:紫色 
46:深绿 
47:白色
\33[90m -- \33[97m 黑底彩色
90:黑 
91:深红 
92:绿 
93:黄色 
94:蓝色 
95:紫色 
96:深绿 
97:白色


\33[nA 光标上移n行 
\33[nB 光标下移n行 
\33[nC 光标右移n行 
\33[nD 光标左移n行 
\33[y;xH设置光标位置 
\33[2J 清屏 
\33[K 清除从光标到行尾的内容 
\33[s 保存光标位置 
\33[u 恢复光标位置 
\33[?25l 隐藏光标 
\33[?25h 显示光标
print "\033[32;0m %s"%('aaaaaaa')
print("\033[1;31;40mhello world\033[0m")  
print("\033[0;31m%s\033[0m" % "bbbbbbbb")
print("\033[0;31m%s\033[0m" % "bbbbbbbb")
print("\033[1;31;43mhello world\033[0m")  


print('This is a \033[1;35m test \033[0m!')
print('This is a \033[1;32;43m test \033[0m!')
print('\033[1;33;44mThis is a test !\033[0m')


s="hello world"
t='hello'
print s.replace(t,'\033[1;31;40m%s\033[0m'%(t))

2.Table:how to print tables in terminal like in mysql

#!encoding=utf-8
from pylsy import pylsytable
# First, you need to create a list, which will contain the table attributes:
attributes=["name","age","sex","id","time"]
# Then feed it to PylsyTable to create the table object:
table=pylsytable(attributes)
# Now populate the attributes with values. Prepare a list for the names:
name=["sun","lsy","luna"]
# Add the data into it:
table.add_data("name",name)
# If you want to insert some extra values to the same column,
# you can pass a list as a parameter:
table.append_data("name",["leviathan"])
# Just a single value is OK too:
table.append_data("name",u"xxx") # Note: everything will be coerced to unicode strings.
# Now with all your attributes and values, we can create our table:
#print(table)
table.add_data('age',[1,2,3,4,5])
print(table.__str__()) # The raw unicode-enabled string. Think as `table.__unicode__()`.

3.How to get standard input

st = raw_input("Enter your word:")
print 'i',st

4.print without \n in python

#if python2:
print x,

#if python3:
print(x, end="")

5.textwrap makes text pretty

The textwrap module can beused to format text for output in situations wherepretty-printing is desired. It offers programmatic functionalitysimilar to the paragraph wrapping or filling features found inmany text editors.

doc url : https://docs.python.org/2/library/textwrap.html

textwrap.wrap(text[, width[, …]])
Wraps the single paragraph in text (a string) so every line is at most width characters long. Returns a list of output lines, without final newlines.
Optional keyword arguments correspond to the instance attributes of TextWrapper, documented below. width defaults to 70.

textwrap.fill(text[, width[, …]])
Wraps the single paragraph in text, and returns a single string containing the wrapped paragraph. fill() is shorthand for
"\n".join(wrap(text, ...))
In particular, fill() accepts exactly the same keyword arguments as wrap().

textwrap.dedent(text)
Remove any common leading whitespace from every line in text.
This can be used to make triple-quoted strings line up with the left edge of the display, while still presenting them in the source code in indented form.
Note that tabs and spaces are both treated as whitespace, but they are not equal: the lines ” hello” and “\thello” are considered to have no common leading whitespace. (This behaviour is new in Python 2.5; older versions of this module incorrectly expanded tabs before searching for common leading whitespace.)
For example:

def test():
    # end first line with \ to avoid the empty line!
    s = '''\
    hello
      world
    '''
    print repr(s)          # prints '    hello\n      world\n    '
    print repr(dedent(s))  # prints 'hello\n  world\n'
Demo1
#coding=utf-8
from textwrap import *

def test_wrap():
    test_str = '''\
    The textwrap module provides two convenience functions, wrap() and fill(), as well as 1
    TextWrapper, the class that does all the work, and two utility functions, dedent() and indent(). If 2
    you’re just wrapping or filling one or two text strings, the convenience functions should be good 3
    enough; otherwise, you should use an instance of TextWrapper for efficiency. 4
    '''

    t = wrap(test_str,50)
    print '\n'.join(t)
    print(fill(test_str, 50))
    print(indent(test_str))


def main():
    test_wrap()

if __name__ == '__main__':
    main()
Demo2
#coding=utf-8
import textwrap
text_example='''
You say that you love rain, but you open your umbrella when it rains.
You say that you love the sun, but you find a shadow spot when the sun shines.
You say that you love the wind, but you close your windows when wind blows.
This is why I am afraid, you say that you love me too.
'''
#直接fill是未去除缩进的格式化版本
fill_example=textwrap.fill(text_example)
#dedent用来去除缩进
dedented_text=textwrap.dedent(text_example)
#结合dedent去除缩进+fill传入width参数来设置文本按照某个特定宽度显示
#strip(str)的作用是去除开头和结尾的制定字符 当参数空白时删除空白字符(包括'\n', '\r',  '\t',  ' ')
text_width_limited=textwrap.fill(dedented_text.strip(),30)
#fill的另外一种用法可以单独设置第一行的缩进和剩余几行的缩进
#现在设置第一行缩进一个空格,其他的悬挂于第一行下
text_hanging_indent=textwrap.fill(dedented_text.strip(),
                                      initial_indent= ' ',# 第一行的缩进值
                                      subsequent_indent='  ' * 4,# 后续几行的缩进值
                                      width=45,
                                     )
#打印输出各种格式化结果
print 'No dedent:\n',fill_example,'\n'
print 'Dedented:\n',dedented_text,'\n'
print 'Width Limited:\n',text_width_limited,'\n'
print 'Hanging Effect:\n', text_hanging_indent,'\n'
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值