Python字符串的常用操作

说明:仅供本人复习所用

一、字符串的格式化方法
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
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值