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

本文介绍了Python中两种常见的字符串连接方法及字符串比较,并提醒开发者避免使用某些关键字作为变量名,同时展示了如何通过for循环遍历字符串列表。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

字符串连接


方法一:


>>> str1 = 'hello'  
>>> str2 = 'world'  
>>> str1_2 = str1 + ' ' + str2  
>>> str1_2  
'hello world'  
>>> print str1_2  
hello world  
>>>  

>>> str1 = 'hello'
>>> str2 = 'world'
>>> str1_2 = str1 + ' ' + str2
>>> str1_2
'hello world'
>>> print str1_2
hello world
>>>



方法二:


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

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


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

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



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

字符串比较

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



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

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

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

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

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

>>> str1 = 'hello'  
>>> i = 5  
>>> str2 = str(i)  
>>> print str2  
5  


2. 要理解for x in yyy:中x不是关键词,而是一个我们定义的变量,python每次循环为这个变量赋值yyy中的1个(从最小到最大序号)。
如:
>>> str1 = ['str1', 'str2', 'str3']  
>>> for each in str1: #这里的each可以是任何变量名  
...     print each,  
...  
str1 str2 str3  
>>>  

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值