-
- 切割与拼接
s = 'I love more than i can say' # 按照指定的内容进行切割,默认按照空白(空格、\n、\t) # ret = s.split(sep='o') # 指定最大切割次数,默认不限制 # ret = s.split(maxsplit=2) # 从右边开始切割 ret = s.rsplit(maxsplit=1) print(ret) s = 'hello\nworld' # 按照换行进行切割 print(s.splitlines()) lt = ['how', 'are', 'you'] # 按照指定的内容进行拼接 s = ' '.join(lt) print(s)
- 查找
s = 'Hi buddy! If you have something to say, then say; If you have nothing to say, then go!' # 返回首次出现的下标,没有找到返回-1 # ret = s.find('buddy') # ret = s.find('If') # ret = s.find('hello') # 功能同上,从右边查找 # ret = s.rfind('If') # 统计字符串出现的次数 ret = s.count('If') print(ret) # 判断是否是以指定内容开头 print(s.startswith('Hi')) # 判断是否是以指定内容结尾 print(s.endswith('xxx'))
- 更改
s = 'hello World' # 全大写 print(s.upper()) # 全小写 print(s.lower()) # 大小写转换 print(s.swapcase()) # 首字母大写 print(s.capitalize()) # 每个单词首字母大写 print(s.title()) # 替换 print(s.replace('l', 'L'))
- 判断
# 是否是全大写 print('HELLO'.isupper()) # 是否是全小写 print('hello'.islower()) # 是否是每个单词首字母都大写 print('Hello world'.istitle()) # 是否是全数字 print('1234'.isdecimal()) # 是否是全字母 print('abc123'.isalpha()) # 是否是数字或字母 print('abc123'.isalnum()) # 是否是合理的标识符 print('1hello'.isidentifier())
- 对齐与填充
# 左对齐,右侧填充指定内容,默认填充空格 print('abc'.ljust(5, '*') + 'AAA') # 右对齐,左边填充 print('abc'.rjust(5, '#')) # 居中对齐,两边填充 print('abc'.center(5, '$'))
练习:
- 计算1~100之间所有奇数的和
- 打印字符a~z
- 从终端输入10个字符,大写转小写,小写转大写,其他字符不变,然后输出
- 将12345转换为54321
- 将12345转换为'12345',不要使用str
- 将'12345'转换为12345,不要使用int
- 遍历列表,打印:我叫name,今年age岁,家住dizhi,电话phone
lt = [ {'name':'小王', 'age':18, 'info':[('phone', '123'), ('dizhi', '广州')]}, {'name':'小芳', 'age':19, 'info':[('phone', '789'), ('dizhi', '深圳')]}, {'name':'小杜', 'age':22, 'info':[('phone', '567'), ('dizhi', '北京')]}, {'name':'小孟', 'age':28, 'info':[('phone', '000'), ('dizhi', '上海')]}, {'name':'小乔', 'age':26, 'info':[('phone', '111'), ('dizhi', '河南')]} ]
- 打印九九乘法表
- 从终端输入两个整数m和n,打印m*n的表格,如:2,5,打印如下图形:1 2 3 4 56 7 8 9 10
关注公众号,免费刷快排。
转载请说明出处
奇点seo » python :字符串操作
奇点seo » python :字符串操作