Python学习笔记——String、Sequences

一、input()与raw_input()的区别

 

ContractedBlock.gif ExpandedBlockStart.gif 代码
 
   
1 >>> buck = input( " Enter your name: " )
2 Enter your name: liu
3
4 Traceback (most recent call last):
5 File " <pyshell#1> " , line 1 , in < module >
6 buck = input( " Enter your name: " )
7 File " <string> " , line 1 , in < module >
8 NameError: name ' liu ' is not defined
9   >>> buck = raw_input( ' Enter your name: ' )
10 Enter your name: liu

 

从上面的例子可以看到,raw_input()将输入看作字符串,而input则不是,input()根据输入来判断类型,当然如果你想输入字符串的话就必须在字符串钱加引号。

二、输出的问题

如果我们定义一个整数,然后要将其与字符串同时输出,如下所示

 

ContractedBlock.gif ExpandedBlockStart.gif 代码
 
   
>>> n = 20
>>> print ( ' the num is ' + 20 )

Traceback (most recent call last):
File
" <pyshell#16> " , line 1 , in < module >
print ( ' the num is ' + 20 )
TypeError: cannot concatenate
' str ' and ' int ' objects

 

可见不能直接用加号来表示,解决方法有三种:

第一种可以把n转化为字符串,用str()内建函数:

 

 
  
>>> n = str(n)
>>> print ( ' the num is ' + n)
the num
is 20

 

第二种是加`符号,这个键是在esc键下面的那个,如:

 

 
  
>>> b = 20
>>> print ( ' the num is ' + `b`)
the num
is 20

 

第三种是用占位符,这个类似C语言中的占位符,但要注意连接字符串与其他类型数据的是%而不是逗号

 

 
  
>>> print ( ' the num is %d ' % b)
the num
is 20

 

三、Sequences,这个有点像数组,下面是它的定义与截取(Slicing)

 

ContractedBlock.gif ExpandedBlockStart.gif 代码
 
   
>>> example = [0, 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 ]
>>> example[: 8 ]
[0,
1 , 2 , 3 , 4 , 5 , 6 , 7 ]
>>> example[ - 5 :]
[
5 , 6 , 7 , 8 , 9 ]
>>> example[:]
[0,
1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 ]
>>> example[ 1 : 8 : 2 ]
[
1 , 3 , 5 , 7 ]
>>> example[:: - 2 ]
[
9 , 7 , 5 , 3 , 1 ]

 

 

 

 

 

 

 

 

转载于:https://www.cnblogs.com/liulixiang/archive/2010/05/25/1743488.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值