Python字符串

格式化字符串:
格式化符号 说明
%c 转换成字符(ASCII 码值,或者长度为一的字符串)
%r 优先用repr()函数进行字符串转换(Python2.0新增)
%s 优先用str()函数进行字符串转换
%d / %i 转成有符号十进制数
%u 转成无符号十进制数
%o 转成无符号八进制数
%x / %X 转成无符号十六进制数(x / X 代表转换后的十六进制字符的大
小写)
%e / %E 转成科学计数法(e / E控制输出e / E)
%f / %F 转成浮点数(小数部分自然截断)
%g / %G %e和%f / %E和%F 的简写
%% 输出%


- 用做左对齐
+ 在正数前面显示加号(+)
<sp> 在正数前面显示空格
# 在八进制数前面显示零(0),在十六进制前面显示“0x”或者“0X”(取决于用的是“x”还是“X”)
0 显示的数字前面填充“0”而不是默认的空格
m.n m 是显示的最小总宽度,n 是小数点后的位数(如果可用的话)


str = 'soft ware %s - %f'%('QSY',1.1)
print str
str1 = 'num = %f'%1.26
print str1 
str1 = 'num = %.1f'%1.26
print str1 
str1 = 'num = %03.2f'%1.26234
输出:
soft ware QSY - 1.100000
num = 1.260000
num = 1.3
num = 1.26
print str1 



word = 'version 3.0'
print word.center(20)
print word.center(20,'*')
print word.ljust(20,'*')
print word.rjust(20,'*')
输出:
    version 3.0     
****version 3.0*****
version 3.0*********
*********version 3.0


str2 = "%(str)s : %(num)f" %{"str" : "string","num":1.23} 
print str2
输出:
string : 1.230000


转义字符:
\' 单引号
\" 双引号
\a 发出系统铃声
\b 退格符
\n 换行符
\t 横向制表格
\v 纵向制表格
\r 回车符
\f 换页符
\o 八进制表示字符
\x 十六进制表示字符
\000 终止符

str3 = 'str ==%5s'% 'string'
print str3
str4 = 'value =%5d'%12
print str4
输出:
hello = 'hello\rword\n'
print hello
hello = 'hello\tword\n'
print hello


Python中的strip用于去除字符串的首尾字符,同理,lstrip用于去除左边的字符,rstrip用于去除右边的字符。这三个函数都可传入一个参数,指定要去除的首尾字符。
去掉前后转义字符:
print'-------------------------'
print hello1.strip()
print'-------------------------'
print hello1.lstrip()
print'-------------------------'
print hello1.rstrip()
print'-------------------------'
teststr = 'abcdefab'
print teststr.strip('ab')
print teststr.lstrip('ab')
print teststr.rstrip('ab')
输出:
-------------------------
hello	word
-------------------------
hello	word


-------------------------
	hello	word
-------------------------
cdef
cdefab
abcdef


字符串的合并:
+
join()
reduce()

str1 = 'hello'
str2 = 'word'
str3= 'Python'
print str1+str2+str3
str = ('hello','word','Python')
print ''.join(str)
import operator
result = reduce(operator.add, str)
print result
输出:
hellowordPython
hellowordPython
hellowordPython


字符串的截取:
[]:切片
split():

str = 'ab,cd,ef,gh'
print str[1]
print str[2:]
print str[1:5]
print str[:3]
print str.split()
print str.split(',')
print str.split(',',1)
print str.split(',',2)
输出:
b
,cd,ef,gh
b,cd
ab,
['ab,cd,ef,gh']
['ab', 'cd', 'ef', 'gh']
['ab', 'cd,ef,gh']
['ab', 'cd', 'ef,gh']


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Car12

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值