python笔记-03(字符串)

python的字符串是不可变的,所以对字符串的元素赋值和切片赋值是非法的。

1、使用%对字符串进行格式化

在使用字符串时,我们通常希望能改变字符串中的一些值,这是我们可以通过%对字符串进行格式化。

# 使用%s设置字符串的格式
str = 'what %s you %s'
value = ('are', 'doing')
print(str % value)

输出结果为:
what are you doing

 

2、使用索引的方式设置值

# 使用format方法进行设置,可以使用索引的方式设置值(索引可以是数字也可以是字符串)
print('{},{} and {} are {}'.format('tom', 'tonny', 'jack', 'friends'))
print('{1},{2} and {0} are {3}'.format('tom', 'tonny', 'jack', 'friends'))

输出结果:
tom,tonny and jack are friends
tonny,jack and tom are friends

通过在{}中添加索引数字可以选填字符

 

3、在字符串中包含{}

# 在字符串格式中包含{}
print('{{hello world}}'.format())

输出结果为:
{hello world}

 

4、string模块中的一些常量

# string模块中的部分常量
print(string.digits)
print(string.ascii_letters)
print(string.ascii_lowercase)
print(string.ascii_uppercase)
print('所有可打印的ascii字符的字符串:'+string.printable)
print('所有ASCII标点字符的字符串:'+string.punctuation)

输出结果为:
0123456789
abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ
abcdefghijklmnopqrstuvwxyz
ABCDEFGHIJKLMNOPQRSTUVWXYZ
所有可打印的ascii字符的字符串:0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!"#$%&'()*+,-./:;<=>?@[\]^_`{|}~ 	

所有ASCII标点字符的字符串:!"#$%&'()*+,-./:;<=>?@[\]^_`{|}~

 

5、字符串的一些方法

# 字符串的center方法,通过在字符串的两边添加字符让字符串居中
print('hello world'.center(39))  # 默认为空格
print('hello world'.center(49,'#'))

# 字符串的find方法,在字符串中查找子串,找到返回索引,否则返回-1
print('hello world'.find('lo'))
print('hello world'.find('op'))
print('hello world'.find('l', 4, 9))
print('hello world'.find('l', 3, 9))
print('hello world'.find('d', 3, 11)) # 字符串最后一个元素d索引为10

# 字符串的join方法 合并序列的元素。合并的元素必须都是字符串
seq = ['1','2','3','4']
strs = '+'
print(strs.join(seq))

seq = ['usr','local','tomcat']
strs = '/'
print(strs.join(seq))

seq = ['c:','usr','local','tomcat']
strs = '\\'
print(strs.join(seq))

# lower方法,将所有字母变为小写,title将首字母大写其他为小写
print('HELLO WORLD'.lower())
print('hELLO wORLD'.title()) # 也可以使用capwords方法

# replace方法,将字符串中指定的字符串进行替换
print('hello world'.replace('world', 'python'))

# split方法用于对字符串进行分割
print('1+2+3+4+5+6+7'.split('+')) # 分割成列表

# strip方法用于将字符串的首尾空白去掉
print('   hello world    '.strip())

# translate方法,用于替换字符串中的内容,只能进行单字符替换。在使用时需要先建立转换表
table = str.maketrans('python', 'people', ' ')  # 需要替换的字符长度需要一致,第三个参数表示删除字符串中特定的字符
print(' hello python python hello'.translate(table))





输出结果为:
              hello world              
###################hello world###################
3
-1
-1
3
10
1+2+3+4
usr/local/tomcat
c:\usr\local\tomcat
hello world
Hello World
hello python
['1', '2', '3', '4', '5', '6', '7']
hello world
pelllpeoplepeoplepelll

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值