Python数据结构:序列——字符串

字符串属于序列(sequence),所以序列的相关操作都适用于字符串。字符串不可以被改变,使用某些函数的时候他会返回一个新的值,而不是改变原字符串

此外还有一些字符串特有的属性:

1. 字符串格式化 %——格式化字符串 % 需要放到格式化字符串的值

%s, %.3f, %c 都是conversion specifier 转换说明符,标记了需要插入values 的位置,限定字段宽时保留的最小最小最小字符串个数(不够补足,够了不会砍掉)

format = 'Hello, %s. %s dollar enough for ya' # %s :
#values should be map(dict) or tuple,other type will be only one value not two or more values
values = ('world',59)
value_list = ['world',59] # list represent only on value
values_nopar = 1, 59 # it's tuple but no parentheses may cause error
print format,values
print format % values
#print format % value_list # list just represent one values
print format % values_nopar #  parentheses is better in case error cause

format = 'Now the process is:%.3f %%' # %% represent %
format0 = 'Now the process is:%15.3f %%' # %% represent %
format00 = 'Now the process is:%1.3f %%' # %% represent %
from math import  pi
print format0 % (pi *1000),'\n', format00 % (pi *1000)

print 'Using str: %s' % 42L
print 'Using repr: %r' % 42L
print 'This is hexadecimal %x' % 42
print ('%5d' % 10 ),'\n',('%5d' % -10)
print '%-10.2f' % pi
print '%010.2f' % pi # not oct number
格式化字符串 这部分据观察,基本上是字符串格式,所以要加上引号——'格式化字符串' / "格式化字符串"
实际应用:(缺陷是如果输入的值比较小,那么肯能会出现对不齐的现象)

width = input('Please enter width:')
price_width = 10
item_width = width - price_width

header_format = '%-*s%*s'#- represent left justifying
format = '%-*s$*.2f'

print '=' * width
print header_format % (item_width,'Item',price_width, 'Price')
print header_format % (item_width,'Pears',price_width, 0.5)
print header_format % (item_width,'cantaloupes',price_width, 1.92)
print header_format % (item_width,'Dried Apricots (16 oz.)',price_width, 8)

2. find 方法找到首字母索引并返回——不改变原字符串

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值