---
title: "python字符串操作（连接、比较、格式化等）"
author: "canlynet"
date: "2010-05-25T17:19:10Z"
tags: ["C", "C#", "C++", "Python"]
categories: ["编程语言"]
slug: "python"
draft: false
lastmod: "2010-05-25T17:53:34Z"
id: 675250
url: "https://canlynet.iteye.com/blog/675250"
---

\[b]字符串连接\[/b] 方法一： \[code="python"]&gt;&gt;&gt; str1 = 'hello' &gt;&gt;&gt; str2 = 'world' &gt;&gt;&gt; str1\_2 = str1 + ' ' + str2 &gt;&gt;&gt; str1\_2 'hello world' &gt;&gt;&gt; print str1\_2 hello world &gt;&gt;&gt;\[/code] 方法二： \[code="python"]&gt;&gt;&gt; str12 = '%s %s' % (str1, str2) &gt;&gt;&gt; print str12 hello world\[/code] 注意，下面方式是利用str1，str2初始化一个元组： \[code="python"]&gt;&gt;&gt; str\_12 = str1, str2 &gt;&gt;&gt; str\_12 ('hello', 'world') #方括弧才是列表，元组是不可改变滴 &gt;&gt;&gt; str\_1\_2 = \['hello', 'world'] &gt;&gt;&gt; str\_1\_2 \['hello', 'world'] #另外顺便提一下，print末尾加逗号是把换行符替代成一个空格的意思。 &gt;&gt;&gt; print 'hello',\\ ... 'world' hello world \[/code] =============================================== \[b]字符串比较\[/b] \[code="python"] &gt;&gt;&gt; str = 'info' #我就犯这个错误，因为c中用str做变量很简洁 &gt;&gt;&gt; cmp(str, 'info') 0 &gt;&gt;&gt; str == 'info' #返回值类型不同！！！尽管if语句中都能使用... True\[/code] ================================================= \[b]字符串注意事项：\[/b] 1. 不要像C语言那样使用str作为变量，因为str在python中是一个关键字，用于转换成字符串类型。 \[code="python"] &gt;&gt;&gt; str = 'hello' &gt;&gt;&gt; i = 5 &gt;&gt;&gt; str1 = str(i) Traceback (most recent call last): File "", line 1, in TypeError: 'str' object is not callable \[/code] 退出python后重新进入（只能退出重新运行，因为这里不是命令行而是python在对stdin进行解释执行（跟读入一个文件执行是一个道理，不过每次都要等待输入一行而已，行缓冲）： \[code="python"]&gt;&gt;&gt; str1 = 'hello' &gt;&gt;&gt; i = 5 &gt;&gt;&gt; str2 = str(i) &gt;&gt;&gt; print str2 5\[/code] 2. 要理解for x in yyy:中x不是关键词，而是一个我们定义的变量，python每次循环为这个变量赋值yyy中的1个（从最小到最大序号）。 如： \[code="python"] &gt;&gt;&gt; str1 = \['str1', 'str2', 'str3'] &gt;&gt;&gt; for each in str1: #这里的each可以是任何变量名 ... print each, ... str1 str2 str3 &gt;&gt;&gt; \[/code]