python字符串操作(连接、比较、格式化等)(转)

字符串连接
方法一:
Python代码

1 >>> str1 = 'hello'
2 >>> str2 = 'world'
3 >>> str1_2 = str1 + ' ' + str2
4 >>> str1_2
5 'hello world'
6 >>> print str1_2
7 hello world
8 >>>

方法二:
Python代码

1 >>> str12 = '%s %s' % (str1, str2)
2 >>> print str12
3 hello world

注意,下面方式是利用str1,str2初始化一个元组:
Python代码

 1 >>> str_12 = str1, str2
 2 >>> str_12
 3 ('hello', 'world')
 4 #方括弧才是列表,元组是不可改变滴
 5 >>> str_1_2 = ['hello', 'world']
 6 >>> str_1_2
 7 ['hello', 'world']
 8 #另外顺便提一下,print末尾加逗号是把换行符替代成一个空格的意思。
 9 >>> print 'hello',\
10 ... 'world' 
11 hello world

===============================================

字符串比较
Python代码

1 >>> str = 'info' #我就犯这个错误,因为c中用str做变量很简洁
2 >>> cmp(str, 'info')
3 0
4 
5 >>> str == 'info' #返回值类型不同!!!尽管if语句中都能使用...
6 True

 

 

=================================================

字符串注意事项:
1. 不要像C语言那样使用str作为变量,因为str在python中是一个关键字,用于转换成字符串类型。
Python代码

1 >>> str = 'hello'
2 >>> i = 5
3 >>> str1 = str(i)
4 Traceback (most recent call last):
5   File "<stdin>", line 1, in <module>
6 TypeError: 'str' object is not callable

退出python后重新进入(只能退出重新运行,因为这里不是命令行而是python在对stdin进行解释执行(跟读入一个文件执行是一个道理,不过每次都要等待输入一行而已,行缓冲):
Python代码

1 >>> str1 = 'hello'
2 >>> i = 5
3 >>> str2 = str(i)
4 >>> print str2
5 5

2. 要理解for x in yyy:中x不是关键词,而是一个我们定义的变量,python每次循环为这个变量赋值yyy中的1个(从最小到最大序号)。
如:
Python代码

1 >>> str1 = ['str1', 'str2', 'str3']
2 >>> for each in str1: #这里的each可以是任何变量名
3 ...     print each,
4 ...
5 str1 str2 str3
6 >>>

 

posted @ 2014-04-15 16:18  幻星宇  阅读(503)  评论(0编辑  收藏  举报