1. 输出
- >>> print "hello world"
- hello world
- >>> print 'hello world'
- hello world
- >>> print 'Hello','world'
- Hello world
- >>> print "I'm studing python"
- I'm studing python
- >>> print 'I am studing "python"'
- I am studing "python"
- >>> print "I'm studing \"python\""
- I'm studing "python"
- >>> print 'I\'m studing "python"'
- I'm studing "python"
- >>> print '''I'm studing "python"'''
- I'm studing "python"
- >>> print '''I am
- ... studing
- ... "python"'''
- I am
- studing
- "python"
- >>> print "Name:%s Age:%d Height:%f" %('Tester',18,1.80)
- Name:Tester Age:18 Height:1.800000
- >>> print "Name:%8s Age:= Height:%5.2f" %('Tester',18,1.80)
- Name: Tester Age: 18 Height: 1.80
- >>> print "Name:%-8s Age:%-3d Height:%-5.2f" %('Tester',18,1.80)
- Name:Tester Age:18 Height:1.80
- >>> print "Name:%s Age:= Height:%*.*f" % ('Tester',18,6,2,1.80)
- Name:Tester Age: 18 Height: 1.80
- print "Name:%r Age:%r Height:%r" %('Tester',18,1.80)
- Name:'Tester' Age:18 Height:1
- >>> print '12',3
- 12 3
- >>> print '12'+3
- Traceback (most recent call last):
- File "<stdin>", line 1, in <module>
- TypeError: cannot concatenate 'str' and 'int' objects
- >>> print '12'+'3'
- 123
- >>> print 12+3
- 15
总结:
1) print 输出字符串可以使用''或者"" 表示;
2) print 后可以有多个输出,以逗号分隔,最终逗号以空格输出,两边类型可以不一致;
也可以用 + 号连接,但是 + 号要求两边类型必须一致,连接数字表示相加,连接字符串表示相连;
3) 如果字符串本身包含 "",可以使用''来表示;如果字符串本身包含'',可以使用"" 来表示;
4) 如果字符串本身既包含''也包含"",可以使用 \ 进行转义;常用转义字符:\n 换行; \t 制表符; \\ 表示 \ 本身
5) 如果字符串本身既包含''也包含"",也可以使用'''来表示;'''一般用于输出多行文本中;
6) 格式化输出可以指定输出字段的长度,%5.2f 表示输出浮点数的小数点后有 2 位,总共长度为 5 位,默认为右对齐,不足的左侧补空格;
%-5.2f 表示左对齐,长度不足的右边补空格
7) 对于格式未定的字段,可以通过类似 %*.*f % (5,2,1.80) 来设定表示 %5.2f
8) 对于类型不确定的字段输出可以统一用 %r 表示,%r 的格式化指定格式后面再学习。
9) format 输出
2. input / raw_input 输入
- >>> raw_var = raw_input("please input your content:")
- please input your content:Testing python
- >>> print raw_var
- Testing python
- >>> type(raw_var)
- <type 'str'>
- >>>
- >>> var = input("please input your content:")
- please input your content:'Testing python'
- >>> print var
- Testing python
- >>> type(var)
- <type 'str'>
- >>> var = input("please input your content:")
- please input your content:Testing python
- Traceback (most recent call last):
- File "<stdin>", line 1, in <module>
- File "<string>", line 1
- Testing python
- ^
- SyntaxError: unexpected EOF while parsing
- >>>
- >>> raw_var = raw_input("please input your content:")
- please input your content:100+300
- >>> print raw_var
- 100+300
- >>>
- >>> var = input("please input your content:")
- please input your content:100+300
- >>> print var
- 4
- >>> age = input('please input your age:')
- please input your age:18
- >>> print age
- 18
- >>> type(age)
- <type 'int'>
总结:
1) raw_input 将所有输入作为字符串看待,返回也是字符串类型
2) input 没有将所有输入作为字符串看待,所以在输入字符串内容时候需要添加引号,否则会出错
3) input 可以接收表达式,并返回表达式结果
4)input 返回也不一定是字符串类型;如果接收的是带引号的字符串那么返回的才是字符串类型;
来源: