python字符串操作(分割、截取、最少字符删除)

2022-08-10,,,,

字符串分隔

题目描述

•连续输入字符串,请按长度为8拆分每个字符串后输出到新的字符串数组;
•长度不是8整数倍的字符串请在后面补数字0,空字符串不处理。

输入描述:

连续输入字符串(输入2次,每个字符串长度小于100)

输出描述:

输出到长度为8的新字符串数组

示例1

输入

abc
123456789

输出

abc00000
12345678
90000000

解法1

while True:
    try:
        row,str_rows =0, int(input())
        while row <str_rows:
            string = input()
            num = len(string)%8 # 余数
            if num != 0:
                string = string + '0'*(8 - num)
            for i in range(len(string)//8):
                print(string[i*8:i*8+8])
            row += 1
    except:
        break

解法2

while True:
    try:
        a= int(input())
        for i in range(a):
            s=input()
            while len(s)>8:
                print(s[:8])
                s=s[8:]
            print(s.ljust(8,"0"))
    except:
        break

按字节截取字符串

题目描述

编写一个截取字符串的函数,输入为一个字符串和字节数,输出为按字节截取的字符串。但是要保证汉字不被截半个,如"我ABC"4,应该截为"我AB",输入"我ABC汉DEF"6,应该输出为"我ABC"而不是"我ABC+汉的半个"。 

输入描述:
输入待截取的字符串及长度

输出描述:
截取后的字符串

示例1

输入
我ABC汉DEF
6
输出
我ABC

python代码实现:

while True:
    try:
        string,length=input().split()
#         string,length=input(),input()
        res,real_len="",0
        for s in string:
            real_len += len(s.encode("gbk"))
            if real_len <= int(length):
                res+=s
        print(res)
    except:
        break

删除字符串中出现次数最少的字符

题目描述

实现删除字符串中出现次数最少的字符,若多个字符出现次数一样,则都删除。输出删除这些单词后的字符串,字符串中其它字符保持原来的顺序。

注意每个输入文件有多组输入,即多个字符串用回车隔开

输入描述:

字符串只包含小写英文字母, 不考虑非法输入,输入的字符串长度小于等于20个字节。

输出描述:

删除字符串中出现次数最少的字符后的字符串。

示例1

输入

abcdd

输出

dd

 解法1:

while True:
    try:
        string = input()
        new_str = ''
        counts = []
        for c in set(string):
            counts.append(string.count(c))
        for c in string:
            if string.count(c) != min(counts):
                new_str += c
        print(new_str) 
    except:
        break

 解法2:

from collections import defaultdict

while True:
    try:
        strs = input()
        counts = defaultdict(int)
        for s in strs:
            counts[s]+=1
        for s in counts.keys():
            if counts[s]== min(counts.values()):
                strs = strs.replace(s,'')
        print(strs)  
    except:
        break

 

本文地址:https://blog.csdn.net/hyblogs/article/details/107071964

《python字符串操作(分割、截取、最少字符删除).doc》

下载本文的Word格式文档,以方便收藏与打印。