# -*- coding:UTF-8 -*-
def read_str():
###################
# 字符串格式化
###################
# 简单转换,整型、浮点型
'price of eggs:%d' % 42 # output:price of eggs:42
'PI:%f' % pi # output:PI:3.141593
# 字段宽度和精度
'%10f' % pi # output:' 3.141593'
'%10.2f' % pi # output:' 3.14'
'%.2f' % pi # output:'3.14'
# 符号、对齐和用0填充
# 用0填充宽度
'%010.2f' % pi # output:'0000003.14'
# '-'表示左对齐数值
'%-10.2f' % pi # output:'3.14'
###################
# 字符串方法
###################
tag = "<a href=http://www.baidu.com>baidu indexpage</a>"
print 'tag[8:28]=', tag[8:28]
print 'tag[29:-4]=', tag[29:-4]
# 字符串替换 replace
tag.replace("www.baidu.com", "www.caoliu.com")
print 'tag.replace=', tag.replace("www.baidu.com", "www.caoliu.com")
# 字符串连接 join
link = ['', 'user', 'bin', 'env']
url = '/'.join(link)
print 'url=', url
# 字符串分割 split
path = '/user/bin/env'
split = path.split('/')
print split
# 字符串大小写转换
s = 'i love you'
print s.lower() # 小写转换
print s.upper() # 大写转换
# 字符串是否为大小写
print s.islower() # 是否为小写
print s.isupper() # 是否为大写
# title 字符串标题
print s.title() # 所有单词的首字母大写
# count 统计出现次数
print s.count('o')
# find 查找字符串位置,如果不存在,返回-1
print s.find('you')
# split 分割
word = s.split()
print word
# join 合并
string = '-'.join(word).upper()
print string
# replace 替换
s.replace('you', 'lina')
print s
# strip 返回去除字符串两侧(不包括内部)空格的字符串
names = ' hello word '
print names.strip() # output: 'hello world'
# translate 字符串替换,replace用于替换整个字符串,translate用于只替换单个字符,可以同时进行多个替换
if __name__ == '__main__':
read_str()
Python字符串
最新推荐文章于 2024-04-04 09:44:21 发布