首页 > 试题广场 >

表示数字

[编程题]表示数字
  • 热度指数:169699 时间限制:C/C++ 1秒,其他语言2秒 空间限制:C/C++ 32M,其他语言64M
  • 算法知识视频讲解

将一个字符串中所有的整数前后加上符号“*”,其他字符保持不变。连续的数字视为一个整数。


数据范围:字符串长度满足

输入描述:

输入一个字符串



输出描述:

字符中所有出现的数字前后加上符号“*”,其他字符保持不变

示例1

输入

Jkdi234klowe90a3

输出

Jkdi*234*klowe*90*a*3*
一开始用比较麻烦的方法做的,脑子有蒙不转弯。后来一看其实counter那就结束了当再出现重置在前面再加个*就好了十几行的事-.-
不用正则大法的话,全转成list,当为数字在那一位insert(“*”),一旦counter重置在那一位再insert(“*”)就完事了。
以及。。正则大法好

#方法1:正则化
import re
while True:
    try:
        str1=input()
        str1=re.sub('(\d{1,})',r'*\1*',str1) #找到为数字的,长度一个或以上的,在满足的两侧添加*
        print(str1)
    except:
        break

#方法2: 非正则
while True:
    try:
        str1 = list(input())#读取数据
        counter = 0#用于判断是否数字开始或结束
        increaser = len(str1) #读取初始长度
        i=0
        while i <increaser:
            if str1[i].isdigit() != True and counter ==1:#当为数字结尾时(也就是字母起始位置添加)
                str1.insert(i, "*")
                counter = 0
                increaser=increaser+1#由于添加导致元素增加,遍历数+1
            elif str1[i].isdigit() == True and counter == 0:#当为数字起始时
                str1.insert(i, "*")
                counter= 1
                increaser=increaser+1
            i=i+1
        if str1[-1].isdigit() == True:#唯一情况全为数字,最后加上*就是了
            str1.append("*")
        print(''.join(str1))
    except:
        break

#方法3:记录自己脑抽
while True:
    try:
        str1 = input()#读取数据
        str2 = str1#转存数据
        index=[]
        counter = 0#用于判断数字的起始index
        for i in range (len(str2)):
            if str2[i].isdigit() != True:#当不是数字时替换成空格
                str2=str2.replace(str2[i], " ")
                counter=0#一旦出现字母则重设计数器,表示数字字符结束
            elif str2[i].isdigit() == True and counter == 0:#当计数器为0时记录当前index,也就是数字的初始index
                index.append(i)
                counter=counter+1#无视后续数字
        str2=str2.split()#以空格差分,提取出要改变的数字
        for i in range (len(str1)):#本来想用replace,但如果遇到*3*23*233这种顺序就会出错。
            if str1[i].isdigit() == True:#改为抹去str1里全部数字为空格
                str1=str1.replace(str1[i], " ")
        str1 = list(str1)#转换为list元素,由于空格填补,字母数字index不变,就可以用到前面得到的数字起始index
        for i in range (len(str2)):
            str3 = "*"+ str2[i]+"*"#把str1数字项的单个index逐个替换成 "*int*" 的形式
            str1[index[i]] = str3#由于其他项已被替换为空格,直接先根据起始数字index塞到一个元素里就行不管其他空格元素。
        str1=''.join(str1)#转换为string
        str1=str1.split()#删除多余空格元素
        str1=''.join(str1)#再变回string
        print(str1)#打印结果
    except:
        break



编辑于 2021-07-01 17:56:08 回复(0)
while True:
    try:
        s = list(input())
        #print(s)
        res = ""
        n = len(s)
        right = 0
        while right<n:
            if '0'<=s[right]<='9':#若为数字
                res+="*" #首先插入"*"
                while right<n and '0'<=s[right]<='9': #直到下一个字符不是数字
                    res+=s[right]
                    right+=1
                res+="*"#在数字末尾加上"*"
            else: #如果不是数字,则添加至res
                res+=s[right]
                right+=1
        print(res)
    except:
        break

发表于 2021-06-16 20:46:19 回复(0)
import sys
import re


for line in sys.stdin:
    print(re.sub(r'(\d+)', r'*\1*', line.strip()))

发表于 2021-05-17 21:34:40 回复(0)
from itertools import groupby
while 1:
    try:
        a=input()
        c=''
        ss = [''.join(list(g)) for k, g in groupby(a, key=lambda x: x.isdigit())]
        for i in ss:
            if i.isdigit():
                c += '*'+i+'*'
            else:
                c += i
        print(c)
    except:
        break
发表于 2021-05-09 20:26:38 回复(0)
while True:
    try:
        lst = ['1','2','3','4','5','6','7','8','9','0']
        s = input()
        flag = 0
        output = ""
        for i in s:
            if i in lst:
                if flag == 0:
                    output = output + "*" + i
                else:
                    output += i
                flag = 1
            else:
                if flag == 1:
                    output = output + "*" + i
                else:
                    output += i
                flag = 0
        if flag == 1:
            output += "*"
        print(output)
    except:
        break
发表于 2021-04-20 19:57:07 回复(0)
那些通过的人给出的代码都是错的,**能替换个毛线啊,被坑了,自己搞
我的思路:
1、首尾加上一个字符,这是为了应付单个字符的情况
2、判断相邻两个字符是否是数字到其他字符的过渡,是的话后面加上一个*,这里的两种情况用异或判断
比如f3s,f3是过渡,f后面加上*,3s是过渡,3后面加上*,遍历一遍就是f*3*s
while True:
    try:
        string = input()
        out = ''
        string = "a"+string+"a"
        for i in range(len(string)-1):
            if string[i].isdigit() ^ string[i+1].isdigit():
                out += string[i]+'*'
            else:
                out+=string[i]
        print(out[1:])
    except:
        break
发表于 2021-04-14 18:58:52 回复(0)
re,永远嘀神

import re
def add(s):
    return '*'+str(s.group())+'*'

while True:
    try:
        s = input()
        res = re.sub('\d+',add,s)
        print(res)
    except:
        break
发表于 2021-03-30 16:44:24 回复(0)
while True:
    try:
        str = input()
        output = ''
        num_count = 0
        for i in range(len(str)):
            if str[i].isnumeric() == False:
                if num_count > 0:
                    output += '*' + str[i]
                    num_count = 0
                elif num_count == 0:
                    output += str[i]
            elif str[i].isnumeric() == True and num_count == 0:
                output += '*' + str[i]
                num_count += 1
                if i == len(str) - 1:
                    output += '*'
            elif str[i].isnumeric() == True and num_count > 0:
                output += str[i]
                if i == len(str) - 1:
                    output += '*'
        print(output)
    except EOFError:
        break

发表于 2021-03-27 15:29:11 回复(0)
while True:
    try:
        str_input = input()  #输入一个字符串
        
        res = ""   #建立一个空字符串
        
        for s in str_input:    #每个数字的两边都加上*
            if s.isdigit():
                res += '*'+s+'*'   
            elif s == '*': #把字符串中的*临时替换成空格
                res += ' '
            else:
                res += s
        
        res = res.replace('**','') #把**替换掉
        res = res.replace(' ','*') #把空格替换回*

        print(res)  
        
    except:
        break

发表于 2021-03-07 11:27:40 回复(1)
  二 直接正则替换 re.sub(pattern, repl, string, count=0, flags=0)

编辑于 2021-02-27 23:10:31 回复(0)
import sys


for s in sys.stdin:
    pre, output = False, ""
    for c in s.strip():
        if (c.isdigit() and not pre)&nbs***bsp;(not c.isdigit() and pre):
            output += "*"
        output, pre = output+c, c.isdigit()
    if output[-1].isdigit():
        output += "*"
    print(output)

发表于 2020-12-19 15:49:06 回复(0)
"""
1,先将字符串按照要求添加 '*'
2,再设置双指针,查找 '**' 的情况,并替换为 '##'
3,将替换后的字符串合并,同时将 '##' 替换为 '',最后输出
"""
def fun(arr):
        b = []      # 用来存放替换后的字符串
        # 在数字前后添加 '*'
        for i in arr:
            if i.isdigit():
                i = '*' + i + '*'
            b.append(i)
        # 将字符串转化为列表
        b = list(''.join(b))
        
        # 设置双指针找 '**' 的情况,left 记录连续 '*' 出现前的最后一个数字位置,right 记录出现后的第一个数字位置
        left, right = 0, 0
        while (right < len(b)):
            # 1,若当前字符是数字,那么对连续出现的 '*' 进行统计判断
            if b[right].isdigit():
                left = right 
                right += 1
                # 若 '*' 连续出现,则将 right 定位到遍历完之后第一个非 '*' 字符的位置
                while (right < len(b)) and (b[right]=='*'):
                    right += 1
                # 若 '*' 连续出现次数为2,说明'**' 为相邻两个数字调整形成的,
                if (right < len(b)) and (right - left == 3):
                    b[left+1] = '#'
                    b[right-1] = '#'
            # 2,若当前字符不是数字,那么直接往后走
            else:
                right += 1
                
        return ''.join(b).replace('##', '')  # 相邻数字经过上面的操作,之间夹'**'
    
    
if __name__=='__main__':
    while True:
        try:
            a = input().strip()
            print(fun(a))
        except:
            break 

发表于 2020-12-01 17:52:16 回复(0)
# 2020年11月17日17:07:26
while True:
    try:
        string = input()
        str_out = ""
#       判断是否以数字开头  
        if string[0].isdigit():
            str_out += "*"
#       循环判断前后两个字符串是否类型一致,若不一致,加"*"
        for i in range(len(string)-1):
            s, u = string[i], string[i+1]
            str_out += s
            condition1 = s.isalpha() and u.isdigit()
            condition2 = s.isdigit() and u.isalpha()
            if condition1&nbs***bsp;condition2:
                str_out += "*"
#       判断是否以数字结束
        str_out += string[-1]
        if string[-1].isdigit():
            str_out += "*"
        print(str_out)
    except:
        break
        

发表于 2020-11-17 17:38:15 回复(0)
Python 一行解法
import re
while True:
    try:
        print(re.sub(r'([0-9]+)', r'*\1*', input()))
    except:
        break
        


发表于 2020-10-02 19:05:27 回复(0)
思路:遍历所有字符串,判断是否为数字
           数字: 若为第一位,前面加*,
                       其他位, 前面字符为非数字, 该数字前面加*
            非数字: 前面为数字,该字符前面加 *
最后一位判断  加*
while True:
    try:
        inStr = input()
        retList = []
        for i in range(len(inStr)):
            if inStr[i].isdigit():
                #数字:第一位,或者前面为非数字,前面加*
                if i == 0 or not inStr[i-1].isdigit():
                    retList.append('*')
            else:
                #非数字,前面为数字,加*
                if i > 0 and inStr[i-1].isdigit():
                    retList.append('*')
            retList.append(inStr[i])
        if retList[-1].isdigit():
            retList.append('*')
        print(''.join(retList))
    except:
        break
编辑于 2020-09-13 11:14:29 回复(0)
while True:
    try:
        str1 = input()
        replaceList = []
        for one in str1:
            isreplace = False
            if one in replaceList:
                isreplace = True
            if one.isdigit() and not isreplace:
                str1 = str1.replace(one, '*'+one+'*')
                replaceList.append(one)

        print(str1.replace('**',''))
    except:
        break
发表于 2020-08-30 15:58:20 回复(0)
python用正则简洁一点
import re
while True:
    try:
        l = input()
        res = re.sub(r'(\d+)',r'*\1*', l)
        print(res)
    except:
        break 

发表于 2020-08-16 22:44:11 回复(0)