Python .format(),%格式化时,对字符串编码方式的影响

1、当标准字符串和Unicode字符串在表达式中混合用时,标准字符串将被自动转换为Unicode字符串。例如:

s = "hello"
t = u"world"
w = s + t     #w = unicode(s) + t
2、当一个字符串方法中使用到Unicode字符串时,结果也总将是Unicode字符串,例如:

a = "Hello World"
b = a.replace("World",u"Bob")   #b = u"Hello Bob"
此外,使用replace()方法进行零替换(结果仍是原始字符)时,结果仍然会是Unicode字符串。

3、如果一个Unicode字符串使用%操作符做格式字符串,所有参数在一开始都将强制换换位Unicode,然后再根据格式规则连接在一起,如果Unicode对象被用作%操作符的一个参数,整个结果也将是Unicode字符串,例如:

c = "%s %s"%("Hello",u"World")#c = "Hello" + u"World"
d = u"%s %s"%("Hello","World")#d = u"Hello" + u"World"
 4、当使用Unicode字符串时,str()和repr()函数会自动使用默认编码将Unicode字符串转换为标准字符串。对于一个Unicode字符串u,str()相当于u.encode(),repr(u)相当于u"%s"%repr(u.encode('unicode-escape'))
5、而对于format来说,则取决于string字符串类型,format参数将自动转化为与string相同的类型

	1. s = "hello"  
	2. t = u"world"  
	3. com = "check {}".format(s)  
	4. print type(com)    
	5. 总结%格式化,
	6. s = "hello"  
	7. t = u"world"  
	8. recom =  "hello %s"%s  
	9. print type(recom)
	10. 当string为Unicode类型时,%参数无论是什么类型,都将转为Unicode类型。   
	11. 而当string不是Unicode类型时,格式化之后的字符串类型就是%参数的类型
	12.  


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值