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