python004 -- 字符串处理及编码格式

2.1 字符串

2.1.1 字符串转换

1
2
3
4
5
6
7
8
9
10
>>> a  =  123    
>>> b  =  1.23
>>>  type (a)
< type  'int' >
>>>  type (b)
< type  'float' >
>>>  type ( str (a))
< type  'str' >
>>>  type ( str (b))
< type  'str' >

说明:先定义个整数和浮点数,再查看类型,用str()函数将对象转成字符串。

这里的用到了type()函数,用于查看对象类型。这个type()在以后学习中很用的,刚开始学习时候,往往因为对象类型不对,导致程序运行报错,这时可以用它来排查问题。 

2.1.2 字符串连接

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
# 加号字符将同类型字符连接到一起    
>>> hw  =  "Hello"  +  "World!"
>>>  print  hw
HelloWorld!
# 两个相邻的字符串自动连接一起
>>> hw  =  "Hello" "World!"
>>>  print  hw
HelloWorld!
# 如果字符串内包括单引号或双引号,要用\转义,否则报错,上一章也讲过。
>>> hw  =  "Hello \"World!\""
>>>  print  hw
Hello  "World!"
# 不同字符串类型拼接
>>> a  =  "abc"
>>> b  =  1
>>>  print  +  b
Traceback (most recent call last):
  File  "<stdin>" , line  1 in  <module>
TypeError: cannot concatenate  'str'  and  'int'  objects
说明:不同字符串类型不允许连接,想要连接可以下面这么做。
方法 1
>>> c  =  "%s%d"  % (a,b)
>>>  print  c
abc1
方法 2
>>> c  =  +  str (b)
>>>  print  c
abc1

2.1.3 格式化输出

操作符号

说明

%s

字符串(str())

%r

字符串(repr())

%d

整数

%f

浮点数,可指定小数点后的精度

1) 字符串格式输出三种方法

1
2
3
4
5
6
7
>>> xxoo  =  "string"    
7
>>> xxoo  =  "string"    
>>>  print  "%s"  % xxoo
相关文章
相关标签/搜索