说明:仅供本人复习所用
一、字符串的格式化方法
name = '小明'
age = '18'
parameter = {
'name': '小明',
'age': '18',
}
print(name + '的年龄是' + age + '岁')
print('%s的年龄是%s岁' % (name, age))
print('{}的年龄是{}岁'.format(name, age))
print('{name}的年龄是{age}岁'.format_map(parameter))
print(f'{name}的年龄是{age}岁')
# 小明的年龄是18岁
二、字符串的常见操作
s = 'hello world!'
print(len(s)) # 12
print(max(s)) # w
print(min(s)) # ''
print(s.find('o', 5, 8)) # 7 找不到返回-1
print(s.rfind('o')) # 7
print(s.index('o')) # 4 找不到报错
print(s.rindex('o')) # 7
print(s.count('o')) # 2
print(s.replace('o', 'O', 1)) # hellO world!
print('**你好**'.strip('*')) # 你好
print('**你好**'.lstrip('*')) # 你好**
print('**你好**'.rstrip('*')) # **你好
print(s.split(' ')) # ['hello', 'world!']
print('hello\nworld!'.splitlines()) # ['hello', 'world!']
print(s.startswith('h')) # True
print(s.endswith('!')) # True
print(s.upper()) # HELLO WORLD!
print('HELLO WORLD!'.lower()) # hello world!
print(s.isalpha()) # False
print('123123'.isdigit()) # True
print(s.isalnum()) # False
print(s.isascii()) # True
print(s.isdecimal()) # False
print(s.isidentifier()) # False
print(s.isprintable()) # True
print(' '.isspace()) # True
print(s.istitle()) # False
print(s.isupper()) # False
print(s.islower()) # True
print(s.isnumeric()) # False
print(s.title()) # Hello World!
print(s.capitalize()) # Hello world!
print('HELLO WORLD!'.casefold()) # hello world!
print('hello WORLD!'.swapcase()) # HELLO world!
print(s.zfill(20)) # 00000000hello world!
print('*'.join(s)) # h*e*l*l*o* *w*o*r*l*d*!
print(s.ljust(20, '*')) # hello world!********
print(s.rjust(20, '*')) # ********hello world!
print(s.center(21, '*')) # *****hello world!****
print(s.partition('o')) # ('hell', 'o', ' world!')
print(s.rpartition('o')) # ('hello w', 'o', 'rld!')
print('hello\tworld!'.expandtabs()) # hello world!
print(ord('a')) # 97
print('hello'.translate(str.maketrans('l', '8'))) # he88o