이 페이지는 코딩도장 데이터의 읽기 전용 정적 보관본입니다.

Every Other Digit

모든 짝수번째 숫자를 * 로 치환하시오.(홀수번째 숫자,또는 짝수번째 문자를 치환하면 안됩니다.) 로직을 이용하면 쉬운데 정규식으로는 어려울거 같아요.

Example: a1b2cde3~g45hi6 → a*b*cde*~g4*hi6

출처:http://regex101.com/quiz/

2014/03/12 16:30

무명소졸

230개의 풀이가 있습니다.

def cnvt(s):
    l = list(s)
    for k in range(1, len(l), 2):
        if l[k].isdigit():
            l[k] = '*'
    return ''.join(l)

2014/03/25 13:50

Mun Kyeongsam

깔끔하네요 ^^ - pahkey, 2014/03/25 17:45
range에서 짝수만 받아올수가 있군요! - soleaf, 2017/04/09 17:17

True, False 가 리스트의 인덱스로 쓰일경우 각각 1,0으로 변환된다는 점을 이용하였습니다.

s = 'a1b2cde3~g45hi6'
print ''.join([[s[i],'*'][i&1==1 and s[i].isdigit()] for i in range(len(s))])

2016/01/19 22:25

상파

[s[i],'*']는 2개 리스트로 홀수일 때 s, 짝수일 때 *,[i&1==1 and s[i].isdigit()]는 0,1값으로 0이면 s,1이면 *가 선택되는군요.멋집니다. - mr. gimp, 2020/03/07 17:26
True, False 에 따른 선택도 가능하군요.. 멋집니다.. - 로만가, 2022/02/08 15:54
import re
print(re.sub(r'((.\D)*)(.)\d((.\D)*)', r'\1\3*\4', 'a1b2cde3~g45hi6'))
# 수정
import re
print(re.sub(r'((((.\D)*)(.)\d((.\D)*))|(.{2}))', lambda x: x.group(8) if x.group(8) else x.group(3) + x.group(5) + '*' + x.group(6), 'a1b2cde3~g45hi6'))

Python 3.5.2에서 작성하였습니다.

SOUP님 글을 보고 수정했습니다. 감사합니다.^^;

2016/12/02 16:57

Yeo HyungGoo

@Yeo HyungGoo님, 이 답이 유일하네요. re.sub 를 이용하여 정규식으로만 푼 해법으로... re.sub 의 patter, repl 를 좀 설명해주시겠어요? 어떻게 동작해서 답이 나오는지 잘 이해가 되지 않아서요??? - 예강효빠, 2017/05/30 07:46
((.\D)*) -> "모든문자 + 숫자가 아닌 문자"를 모두 포함하는 정규식 입니다.(짝수 번째에 문자가 있는 경우를 걸러내기 위한) (.)\d -> "모든문자 + 숫자" 짝수 번째 숫자인 문자를 찾기 위한 정규식 입니다. 홀수 번째 모든 문자와 짝수 번째 숫자를 찾기 위한 정규식 "(.)\d" 앞뒤에 홀수 번째 모든 문자와 짝수 번째 숫자가 아닌 문자를 찾는 정규식을 둬서 짝수 번째 숫자만 찾도록 걸러낸 것 입니다. ((.\D)*)(.)\d((.\D)*)에서 repl의 \1은 첫 번째 ((.\D)*) 이 되고 \2는 \1안쪽에 괄호 (.\D) \3은 (.) \4는 맨 뒤의 ((.\D)*) \5는 \4안쪽에 (.\D)입니다. 따라서 '\1\3*\4'는 "문자 + 숫자가 아닌 문자를 찾은 경우 그 값 없으면 공백" + "문자 + 숫자에서 찾은 문자 + '*'(숫자를 *로 변환)" + "문자 + 숫자가 아닌 문자를 찾은 경우 그 값 없으면 공백"이 반복되면서 치환 되게 하는 것 입니다. 설명이 잘 됐는지 모르겠네요..^^;; - Yeo HyungGoo, 2017/05/30 09:54
설명 정말 감사합니다. 근데 아직도 이해가 잘... Regex101 에 올려서 비교해보고 있는데요. 설명하고 안맞는게 있어서 너무 헷갈리네요. 휴... - 예강효빠, 2017/05/31 12:13
+1 지나가다가 정규표현식 풀이를 봤는데요. 'aa1'과 같은 경우에는 fail이 발생하는 것 같습니다. - SOUP, 2017/07/11 14:04
엄청 빠르게 보셨네요. 저도 글 보고 re.sub 함수를 처음 알아서 큰 도움 받았습니다. :) - SOUP, 2017/07/12 09:25
댓글이 달리면 메일이 오더라고요..ㅎㅎ.^^; 감사합니다. - Yeo HyungGoo, 2017/07/12 09:49

간단하게 생각해서 짜봤습니다 ㅋㅋ Java입니다

뭐 간단합니다
String으로 입력을 받은 후, char c[입력글자수] 배열을 만들어서 한글자씩 집어넣습니다
집어넣으면서 짝수(0부터 시작하므로 i%2==1)번째가 char형 숫자'0'~'9'이면 '*'를 대입합니다
package h_everyotherdigit;
import java.util.Scanner;
public class Every_other_digit {
    public static void main(String[] args) {
        Scanner in=new Scanner(System.in);
        String s=in.next();
        int L=s.length(), i;
        char[] c=new char[L];
        for(i=0;i<L;i++){
            c[i]=s.charAt(i);
            if(i%2==1){
                switch(c[i]){
                case'0': case'1': case'2': case'3':case'4': case'5': case '6': case '7': case '8': case '9':
                    c[i]='*'; break;             
                }
            }
            System.out.print(c[i]);         
        }
    }
}
#실행예시
d12abc3wf98we8fe23jh522fk23hf329f2face32fao325l23
d*2abc3wf*8we*fe2*jh5*2fk*3hf*2*f*face3*fao*2*l*3
c[]={'0','1', ... , '9'}일 때, (int)c[i]를 알아보니까,
48 49 50 51 52 53 54 55 56 57 이더군요
(즉, char형 숫자('0'~'9')의 int값은 그 숫자에 +48을 한 것입니다)
따라서, (int n;) n=(int)c[i]; →if(n>=48 && n<=57)이면 이 char형 c[i]는 숫자값을 가지고 있는 것입니다.
다시 짜봤습니다. 실행결과는 위와 같았습니다.
package h_everyotherdigit;
import java.util.Scanner;
public class Every_other_digit {
    public static void main(String[] args) {
        Scanner in=new Scanner(System.in);
        String s=in.next();
        int L=s.length(), i, n;
        char[] c=new char[L];
        for(i=0;i<L;i++){
            c[i]=s.charAt(i);
            n=(int)c[i];
            if(i%2==1 && n>=48 && n<=57) c[i]='*';
            System.out.print(c[i]);         
        }
    }
}

2014/03/12 22:39

Katherine

정규식을 활용해봤습니다. 자바스크립트입니다.

문제의 조건을 다음과 같이 재구성해보았습니다.

1) 모든 짝수번째 숫자를 *로 치환한다.

2글자에 매치하는 정규식을 만들자. 문자열 길이가 홀수인 경우 맨 마지막 문자의 순서는 홀수이므로 1글자로 인식할것이다. 즉, 정규식 매치가 안될것이다.

2) 홀수번째 숫자, 또는 짝수번째 문자를 치환하면 안된다.

홀수번째는 아무 문자나 올수있지만 치환하면 안된다. 짝수번째는 아무 문자나 올수있지만 숫자만 치환한다.

그래서 정규식을 활용해서 뽑아보기로 했습니다. 정규식을 잘 다루는 편이 아니라서 조악하지만 잘 봐주세요 ^^

Javascript

"a1b2cde3~g45hi6".replace(/.(?:([0-9])|[^0-9])/g, function (str, match) {
    return !match ? str : str[0] + "*"
});

Result

a*b*cde*~g4*hi6

2014/04/29 04:38

Lee MooYeol

깔끔하네요 ^^ - pahkey, 2014/04/29 09:37

정규식으로 해 볼려고 했는데.. 너무 어렵네요. ㅜㅜ
정규식은 포기하고 파이썬으로 만들어 봤습니다.

총 3가지 버전입니다.

1번

def everyOtherDigit(s):
    r = ""
    s = list(s)
    for odd, even in zip(s[::2], s[1::2]):
        if '0' <= even <= '9': even = "*"
        r += odd+even
    if len(s)%2: return r+s[-1]
    else: return r

2번

def everyOtherDigit(s):
    r = ""
    for i, c in enumerate(list(s)):
        if i%2 and '0' <= c <= '9': r+="*"
        else: r+=c
    return r

3번

def everyOtherDigit(s):
    s = list(s)
    for i, c in enumerate(s):
        if i%2 and '0' <= c <= '9': s[i]="*"
    return "".join(s)

2014/03/13 01:08

pahkey

clojure

(apply str (for [[i c] (map-indexed vector "a1b2cde3~g45hi6")]
             (if (and (zero? (mod (inc i) 2))
                      (Character/isDigit c))
               \*
               c)))

2014/03/23 06:44

김 은평

s='a1b2cde3~g45hi6'
r=/^((?:..)*)(.)(\d)/

while s =~ r
  s.gsub! r, '\1\2*'
end

puts s

2014/03/25 13:00

Kim Jaeju

String text = "a1b2cde3~g45hi6";
        StringBuilder value = new StringBuilder();
        for(int i=0; i<text.length(); ++i) {
            String add = "";
            char t = text.charAt(i);
            if(0 != i && i%2 != 0) {
                if(t > 47 && t < 58) {
                    add = "*";
                } else {
                    add = String.valueOf(t);
                }
            } else {
                add = String.valueOf(t);
            }
            value.append(add);
        }

2014/03/28 16:57

김대원

Ruby

def every_other_digit(target)
  target.scan(/./).map.with_index{|c,i|i%2==1 && c=~/[0-9]/?"*":c}.join
end

Test

require 'test/unit'
extent Test::Unit::Assertions

assert_equal every_other_digit("a1b2cde3~g45hi6"), "a*b*cde*~g4*hi6"

2014/04/06 00:49

nacyot

str='a1b2cde3~g45hi6'
strlen=len(str)
for i in range(0,strlen):
    if i % 2 == 1 and str[i]<='9' and str[i]>='0':
       str_c=str.replace(str[i],'*')
       str=str_c
print(str)

2014/04/26 01:30

장 진욱

파이썬입니다.

import re

data = "a1b2cde3~g45hi6"
list_data = list(data)

for num in range(len(list_data)):
        if num % 2 <> 0:
                patturn = re.compile(r"\d")
                list_data[num] = patturn.sub("*", list_data[num])

print "".join(list_data)

결과 입니다.

a*b*cde*~g4*hi6

2014/05/07 13:44

재민스

파이썬3

        
input_list = list('a1b2cde3~g45hi6') output_str = ''

for idx, val in enumerate(range(0, len(input_list))): if idx % 2 != 0: if input_list[idx].isdigit(): input_list[idx] = '*' output_str += str(input_list[idx])

print(output_str)

2014/06/11 15:53

이 수범

예전에 잠깐 배운 정규표현식으로 작성해보았습니다.

#!/usr/bin/env python

# a1b2cde3~g45hi6 -> a*b*cde*~g4*hi6

import re

def main():
    origin_str = "a1b2cde3~g45hi6"
    str_list = list(origin_str)

    print origin_str

    for i in range(1,len(origin_str),2):
        str_list[i] = re.sub(r"\d", "*", str_list[i])

    origin_str = "".join(str_list)
    print origin_str


if __name__ == "__main__":
    main()

아래는 정규표현식 안쓰고 작성한 버전 (문자열 크기 비교로 작성하였습니다.)

#!/usr/bin/env python

# a1b2cde3~g45hi6 -> a*b*cde*~g4*hi6

def main():
    origin_str = "a1b2cde3~g45hi6"
    str_list = list(origin_str)

    print origin_str

    for i in range(1,len(origin_str),2):
        if str_list[i]>='0' and str_list[i]<='9':
            str_list[i]='*'

    str = "".join(str_list)
    print str 

if __name__ == "__main__":
    main()

2014/07/10 17:33

양승은

old_string = 'a1b2cde3~g45hi6'
new_string = ''

for i in range(len(old_string)):
    if i % 2 is 1 and old_string[i].isdigit():
        new_string += '*'
    else:
        new_string += old_string[i]
print new_string

이 문제는 설명은 따로 필요하지않을것같네요 코드가 가장 쉬운 설명같습니다.

2014/07/26 06:31

황 성호

package algorithms.level2.ing;

public class EveryOneDigit2 {

    // 짝수번째 숫자를 *로 치환 
    // Example: a1b2cde3~g45hi6 → a*b*cde*~g4*hi6
    public static void main(String[] args) {
        String data = "a1b2cde3~g45hi6";

        String replaceDigit = replaceDigit(data);
        System.out.println(replaceDigit);
    }

    private static String replaceDigit(String data) {
        StringBuffer stringBuffer = new StringBuffer();
        for(int i=0; i<data.length(); i++){
            char charAt = data.charAt(i);
            if(i % 2 != 0){
                if(Character.isDigit(charAt)){
                    charAt = '*';
                }
            }
            stringBuffer.append(charAt);
        }
        return stringBuffer.toString();
    }
}

두번째

public class EveryOtherDigit {
    public static void main(String args[]){
        String text = "a1b2cde3~g45hi6";
        String replace = "";
        for(int i=0; i<text.length();i++){
            char charAt = text.charAt(i);
            if(i % 2 != 0){
                if(Character.isDigit(charAt)){
                    charAt = '*';
                }
            }
            replace += charAt;
        }
        System.out.print(text + " -> " + replace);
    }
}

2014/07/31 12:46

전 수현

#include <iostream>
using namespace std;

char* str = "a1b2cde3~g45hi6";

void main()
{
    for(int i = 0; i < strlen(str); i++) {
        if(str[i] >= '0' && str[i] <= '9' && (i+1) % 2 == 0) {
            cout << "*" ;
        } else {
            cout << str[i];
        }
    }
    cout << endl;
}

C++이 조금 가미된 C스타일의 코드입니다

2014/08/13 20:36

EC Miny

print "teset"
print "가나"

str = "a123df4sdfd5sfdsfdsf"

def StringTo(Str,ch):
    re =1 # switch
    result=""
    for i in Str:
        re *=-1
        if re>0 and i.isdigit(): # 짝수일때
            i=ch;
        result +=i
# 문자를 하나씩 추가하되 짝수이면 *로 홀수이면 그대로
    return result

print(str)
str = StringTo(str,"*")
print(str)

2014/09/01 15:01

식빵

파이썬 3.4 입니다.

def digit_transform(data):
    result = ""
    for x in range (0,len(data)):
        temp_charac = data[x]
        if temp_charac.isdigit() == True and x%2 == 1:
            temp_charac = "*"
        else:
            pass
        result = result + temp_charac    
    return result

data = input()
print(digit_transform(data))

2014/09/24 19:41

돌구늬ㅋ~썬

자바 소스입니다~ String 형태를 char[]로 만든다음에 인덱스를 2개씩 증가하면서 체크했습니다.

package my_test;
/*
 * 모든 짝수번째 숫자를 * 로 치환하시오.(홀수번째 숫자,또는 짝수번째 문자를 치환하면 안됩니다.) 
 * 로직을 이용하면 쉬운데 정규식으로는 어려울거 같아요.
 * Example: a1b2cde3~g45hi6 → a*b*cde*~g4*hi6
 */
public class T {
    public static void main(String[] args) {
        String str="a1b2cde3~g45hi6";
        System.out.println(change(str));
    }

    public static String change(String str){
        char[] temp = str.toCharArray();
        //아스키코드 48~57 : 0~9
        for(int i=1;i<temp.length;i+=2){
            if(48<=temp[i]&&temp[i]<=57){
                temp[i]='*';
            }
        }
        return String.valueOf(temp);
    }

}

2014/09/26 17:38

임시

// C# 입니다.
using System;
using System.Collections.Generic;

class Program
{
    static string input = "a1b2cde3~g45hi6";

    static void Main()
    {
        char[] inputArray = input.ToCharArray();
        for (var i = 1; i < inputArray.Length; i += 2)
        {
            int number;
            if (Int32.TryParse(inputArray[i].ToString(), out number))
            {
                inputArray[i] = '*';
            }
        }
        Console.WriteLine(input);
        Console.WriteLine("---> " + new string(inputArray));
    }
}

2014/09/29 15:11

보헤미안

void Change(char* input) {
    for(int i = 0; i < sizeof(input); i++) {
        if(i%2 == 1 && (input[i] >= '0' && input[i] <= '9') ) {
            printf("*");
        }
        else
            printf("%c", input[i]);
    }
}

2014/11/14 21:28

좋은게좋은거

// main.go

package main

import ("fmt"; "unicode";"strings")

func main() {
    str := "a1b2cde3~g45hi6"
    for index, runeValue := range str {
        if unicode.IsDigit(runeValue) && index % 2 != 0 {
            str = strings.Replace(str, string(runeValue), "*", -1)
        }
    }
    fmt.Printf(str)
}

2014/12/08 16:39

전 수현

아 진짜 많이 헤맸네요. 근데 짝수번째로 등장하는 숫자를 *로 바꾸면 문제에 있는 예시가 틀린게 아닌가 싶습니다.

2, 4 6 이 *로 치환되어 "a1b*cde3f~g*5hi*"가 나옵니다.

파이썬입니다.

import re

E = "a1b2cde3f~g45hi6"
print re.sub(r'(\d)(.*?)(\d)','\\1\\2*', E)

2014/12/11 16:09

룰루랄라

문제의 예시는 정확합니다. - *IDLE*, 2015/01/13 17:22
아하. 짝수번째 문자가 숫자인 경우에 별표로 치환하는 거로군요 - 룰루랄라, 2015/01/13 18:25

Perl

s/\G((?:..)*?.)(?:\d)/$1*/g

\G는 마지막 매치 위치로 없을 경우 백트래킹되어 마지막 6이 매치됩니다.

2015/01/04 00:47

*IDLE*

python 입니다.

import unittest

def func(arg):
  x = ''
  for i in range(len(arg)):
    if i%2 == 1 and arg[i].isdigit() :
      x = x + "*"
    else : 
      x = x + arg[i]
  return x

class CommaTest(unittest.TestCase):
  def test1(self):
    self.assertEqual('a*b*cde*~g4*hi6', func('a1b2cde3~g45hi6'))


if __name__ == "__main__":
  unittest.main()

2015/01/05 14:28

Sang Brian

ruby입니다.

puts "a1b2cde3~g45hi6".gsub(/((.\D)*.)\d((.\D)*)/, '\1*\3')

어떻게 해야 괄호를 더 줄일 수 있을까요?

2015/01/13 17:15

Shim Won

Scala

def everyOtherDigit(s:String) = {
  s.map(c => if(c.isDigit && s.indexOf(c) % 2 == 1) '*' else c).mkString
}

2015/01/21 23:20

이 호연

coding by python beginner

t0 = 'a1b2cde3~g45hi6'
for i in range( len(t0) ):
    if (i+1) % 2 == 0 and t0[i].isdigit():
        t0 = t0[:i] + '*' +  t0[i+1:]
print(t0)

2015/01/23 13:53

vegan

Using python

import re
a = "a1b2cde3~g45hi6"

a= list(a)
for i in range(1,len(a),2):
    a[i] = re.sub("\\d","*",a[i])

print "".join(a),

2015/03/29 22:11

freeefly


#데이터
string = "a1b2cde3~g45hi6"
src = list(string)        
#처리
def change(src):
    for s_char in range(1, len(src), 2):
        if src[s_char].isnumeric():     
            src[s_char] = "*"           
    return "".join(src)                 
#입출력
print(change(src))

2015/04/03 20:52

zerofury

C#으로 작성했습니다.

using System.Text;

        public string PrintConvertedEventhDigit(string input)
        {
            var output = new StringBuilder();
            for (int i = 0; i < input.Length; i++)
            {
                var curr = input[i];
                if (i%2 == 1 && char.IsDigit(curr)) output.Append('*');
                else output.Append(curr);
            }
            return output.ToString();
        }

2015/04/29 16:12

Straß Böhm Jäger

#include <stdio.h>
#include <ctype.h>
#include <string.h>

int main()
{
  char ss[] = "a1b2cde3~g45hi6";
  int i;

  for(i=0; i<strlen(ss); i++){
    if((i % 2) == 1 && isdigit(ss[i])){
      ss[i] = '*';
    }
  }

  printf("%s\n", ss);

  return 0;
}

2015/05/01 22:56

이 정연

string = "a1b2cde3~g45hi6"

def number( value ):
    try :
        int( value )
        return "*"
    except ValueError:
        return value

def EveryOtherDigit( string ):
    string2 = ""
    for i in range(len(string)):
        if i%2 == 1.0:
            string2 += number( string[i] )
        else : string2 += string[i]
    return string2

print EveryOtherDigit( string )

2015/05/03 15:40

spencer2

#include <iostream>

using namespace std;

int main(){
    char s[] = "a1b2cde3~g45hi6";
    int size = sizeof(s) / sizeof(s[0]);

    cout << s << endl;

    for(int i=0;i<size;i++)
        if((s[i]>47&&s[i]<58)&&!((i+1)%2)) s[i]='*';
        // 짝수번째 인덱스의 문자가 0~9 사이일경우 (아스키코드 48~57 사이) *로 치환

    cout << s << endl;

    return 0;
}

2015/05/06 12:33

구 용현

Python 2

str = 'a1b2cde3~g45hi6'
lst = list(str)
replaced_by_ch = '*'
for x in lst:
    i = lst.index(x) + 1
    if i % 2 == 0:
        if x >= '0' and x <= '9':
            lst[i-1] = replaced_by_ch

2015/05/11 16:45

bbutan

파이썬입니다~

ab=raw_input("input")

print "".join([ab[x]*(x%2)+"*"*((x+1)%2) for x in range(len(ab))])

2015/05/11 16:54

심재용

숫자일 경우에만 *로 바꿔야 합니다. - 상파, 2016/01/19 22:23

c언어

void main() {
    char inputStr[20] = {0,};
    int i;

    printf("입력 : ");
    scanf("%s", inputStr);
    printf("입력된 문자열 : %s \n", inputStr);

    for(inputStr[i]; inputStr[i] != NULL; i++) {
        if(inputStr[i] >= '0' && inputStr[i] <= '9')
            if(inputStr[i] % 2 == 0)
                inputStr[i] = '*';
    }

    printf("변환된 문자열 : %s \n", inputStr);
}

2015/05/16 15:53

Kim Inho

public static string Answers(string Str)
        {
            string Result = "";
            int StrLgh = Str.Length;
            char[] StrC = new char[StrLgh];

            for (int i = 0; i < StrLgh; i++)
            {
                if ((i+1) % 2 == 0 && Str[i] >= 48 & Str[i] < 58)
                {
                    StrC[i] = '*';
                }
                else
                {
                    StrC[i] = Str[i];
                }
            }

            Result = new string(StrC);

            return Result;
        }

2015/06/14 13:16

허 빈

자바공부중인 아마추어입니다. 귀엽게 봐주세요 ㅎㅎ

일단 for문에서 i가 2씩증가하게만들어 짝수 인덱스를 바로바로불러왔구요요 문자의 인덱스는 0... 1.... 2... 3... 과같이 0부터 시작함으로, 위에 2씩증가하는 for문의 i를 -1 씩해주어 육안상 짝수번째 인덱스를 맞추어주었습니다.

숫자판별은.. 아스키코드(10진수)로 48이상 57이하면 숫자입니다. 그러므로 charAt으로 i-1번째 인덱스를 빼와 if조건문으로 위사항을 체크했구요 숫자라면,,, StringBuffer의 replace메소드로.. -> StringBuffer.replace(시작index, 끝index, 변경문자열) 해당인덱스의 문자를 *로 바꾸어주었습니다.

public class Main {


  public static void main(String[] args) {

      StringBuffer str = new StringBuffer("a1b2cde3~g45hi6");

    for (int i = 2; i < str.length(); i += 2) {
        if(str.charAt(i - 1) >= 48 && str.charAt(i - 1) < 58){ // 숫자판별
            str.replace(i-1, i, "*"); }
    }              
      System.out.println(str);
    }

}

2015/06/14 15:48

문성훈

<?php
   $string = "a1b2cde3~g45hi6";
    $a = preg_replace('/((.\D)*.)\d((.\D)*)/','\1*\3', $string);
?>

2015/06/14 19:31

hanjonghoon

Sub Main()
    Dim n As Integer
    Console.WriteLine(String.Join("", Console.ReadLine.ToArray.Select(Function(c As Char) IIf(IsNumeric(c.ToString) And System.Threading.Interlocked.Increment(n) Mod 2 = 0, "*"c, c))))
End Sub

2015/06/14 20:34

Steal

Sub Main()
    Dim n As Integer
    Console.WriteLine(String.Join("", Console.ReadLine.ToArray.Select(Function(c As Char) IIf(IsNumeric(c.ToString) And System.Threading.Interlocked.Increment(n) Mod 2 = 0, "*"c, c))))
End Sub

2015/06/14 20:35

Steal

#include <stdio.h>
#include <string.h>
int main()
{
int i;
char S[10000];
scanf("%s", S+1);
for (i = 1; i <= strlen(S+1); i++)
{
if (i%2 == 0 && S[i] >= '0' && S[i] <= '9')
{
printf("%c", S[i]);
}
else
{
printf("%c", S[i]);
}
return 0;
}

2015/06/15 23:03

배 재완

#include <stdio.h>
#include <Windows.h>

#pragma warning(disable : 4996)
int main()
{
    char str[100];
    printf("Example : ");
    scanf("%s",str);
    for(int i=1; str[i] != NULL;i+=2 )
    {
        if(str[i] >= '0' && str[i] <= '9')
            str[i] = '*';
    }
    printf("\n%s",str);
    system("pause");
    return TRUE;
}

2015/06/17 12:13

심 기용

def even_change(s):
        """
        (str) -> (list) -> str

        This function changes the even number to "*". It does not apply for
        characters.

        >>>even_change("a1b2cde3~g45hi6")
        a*b*cde*~g4*hi6
        """
        l = list(s)
        for i in range (1, len(l), 2):
                if l[i].isdigit():
                        l[i] = "*"
        return "".join(l)

2015/06/18 22:58

Jethro

C입니다

#include<stdio.h>
#include<stdlib.h>
#include<ctype.h>
#include<string.h>
int main(){
    char temp[80];
    char *a;
    gets(temp);
    a = (char *)malloc(strlen(temp)+1);
    strcpy(a,temp);

    for(int i=0;i<strlen(temp)+1;i++){
        if(i%2==1){
            if(isdigit(a[i])){
                a[i]='*';
                printf("%c",a[i]);
            }
            else printf("%c",a[i]);
        }
        else printf("%c", a[i]);
    }
}

2015/06/21 11:41

신영원

string input = "a1b2cde3~g45hi6";

for (int i = 0; i < input.Length; i++ )
    if ((i + 1) % 2 == 0)
        if (input[i] >= 48 & input[i] < 58)
            input = input.Replace(input[i], '*');

Console.WriteLine(input);

2015/06/27 07:04

Raye

자바로 짜봤습니다.

우선 스캐너로 문자열을 입력받은후 입력받은 문자열을 문자배열에 집어넣고 반복문을사용해 문자배열의 사이즈만큼 반복하고 반복구간중 인덱스 코드를 2로나눳을경우 1이 뜨는경우(인덱스코드는 0부터 시작함)중 char형0~9가있으면 그문자대신 *을 넣고 그것을 출력하는식으로 만들어 봤습니다

package dojavn;
import java.util.Scanner;
public class dsa {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        Scanner sc=new Scanner(System.in);

        String ta=sc.nextLine();
        char [] s=ta.toCharArray();

        for(int i=0;i<s.length;i++)
        {
            if(i%2==1){
                if(s[i]>='0'&&s[i]<='9'){
                    s[i]='*';
                }

            }

            System.out.print(s[i]+" ");
        }

    }

}

2015/07/03 04:49

사석훈

a ="a1b2cde3~g45hi6"
for i in range(len(a)):
    if((i%2)==1) & a[i].isdigit() :
        print('*',end='')
    else:
        print(a[i],end='')

a에 문자 입력한후 i를 증가시키면서 a의 길이만큼 반복 i는 0부터 시작하므로 i가 홀수(짝수번째 문자)이고 a[i]번째 문자가 숫자이면 *을 출력 i가 짝수이거나(홀수번째 문자이거나) a[i]번째 문자가 숫자가 아니라면 그대로 출력

2015/07/12 02:14

김 남정

def dit(s):
    r=0
    s = list(s)
    for k in range(0,len(s)) :
        if s[k].isdigit():
            r=r+1
            if r%2==0:
                s[k]='*'

    return "".join(s)

2015/07/13 02:21

seong

파이썬입니다~~ ^^

s = "a1b2cde3~g45hi6"
l = list(s)
def aster( i ): l[i] = '*'
[ aster(i) for i in range(1, len(l), 2 ) if l[i].isdigit() ]
print ''.join(l)

2015/07/18 14:44

Snail Shell Kim

void exce41()
{
    char input[255];
    int count = 0;

    gets_s(input);

    for (int i = 0; i < strlen(input); i++)
    {
        if (input[i] < '9' && input[i] > '0')
        {
            count++;
            if (count % 2 == 0)
                input[i] = '*';
        }
    }

    printf("%s", input);
}

그냥 무난하게 해 봤습니다.

2015/08/17 11:35

조서현


import java.util.Scanner;

public class EveryOtherDigit {

    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        String input = scan.nextLine();
        String result = "";

        for (int i = 0;i<input.length();i++){
            if(i == 0 || i%2 == 0)
                result = result + input.charAt(i);
            else {
                if(input.charAt(i)>=48 && input.charAt(i)<=57)
                    result = result + "*";
                else
                    result = result + input.charAt(i);
            }               
        }       
        System.out.println(result);     
        }
}

2015/08/26 14:29

임 어진

thestring = input(); thestring = list(thestring)
for i in range(0, len(thestring)-1):
    if i%2 == 1:
        thestring[i] = '*'
thestring = "".join(thestring); print(thestring)

입력받은 문자열을 리스트로 변환한 후, 홀수 번째 항을 '*'으로 치환한 뒤 다시 단일 문자열로 재변환하여 출력합니다.

2015/10/07 14:49

박재우

def replace_with_asterisk(text):
    text_list = list(text)
    for i, c in enumerate(text):
        if i % 2 == 1 and 48 <= ord(c) <= 57:
            text_list[i] = '*'
    return ''.join(text_list)

2015/10/23 22:14

Dale Seo

public class substitute implements baseInterface {

    @Override
    public void init() {


        System.out.println("아무 문제나 입력 : ");

        Scanner sc = new Scanner(System.in);

        String str = sc.nextLine();

        System.out.println(str);

        char[] temp = new char[100];


        int lengthStr = str.length();

        for (int i = 0; i < lengthStr; i++) {
            char c = str.charAt(i);

            temp[i] = c;

            if((i+1)%2 == 0){

                if(c<48 || c> 57){ // 문자인 경우
                    temp[i] = '*';
                }
            }       

        }

        str = "";

        for (int i = 0; i < lengthStr; i++) {
            str += temp[i];

        }

        System.out.print(str);




    }

}

2015/10/26 14:34

underProgrammer

파이썬입니다.

def convert_to_star(string):
    listed_string = list(string)
    for i in range(1, len(listed_string), 2):
        if listed_string[i].isdigit():
            listed_string[i] = '*'
    return ''.join(listed_string)

print(convert_to_star("a1b2cde3~g45hi6"))

2015/11/10 13:15

김경호

<?php
    echo encode('a1b2cde3~g45hi6');

    function encode($str)
    {
        for ($i=0; $i < strlen($str); $i++) { 
            if ($i != 0 && $i%2 == 1) {
                if(is_numeric($str[$i])) $str[$i] = '*';
            }
        }

        return $str;
    }

?>

2015/11/24 16:24

한기우

파이썬 2.7


s = 'a1b2cde3~g45hi6'

s = s.replace('', ' ').split()
result = ''

for i in range(len(s)):
    if i % 2 != 0 :
        result += '*'
    else:
        result += s[i]

print result

2015/12/30 12:16

hana11

파이썬 2.7.11


import string

s = 'a1b2cde3~g45hi6'

s = s.replace('', ' ').split()
result = ''

for i in range(len(s)):
    if i % 2 != 0 and s[i] in string.digits:
        result += '*'
    else:
        result += s[i]

print result

2015/12/30 12:27

hana11

  • python으로 작성하였습니다.
s="a1b2cde3~g45hi6"# → a*b*cde*~g4*hi6"
outS=''
for idx,c in enumerate(s):  
    if c.isdigit() and (idx+1)%2==0:
        outS+='*'
    else:
        outS+=c        

print outS

2016/01/08 09:03

씨니컬우기님

숫자인지 문자인지 구분하는 법이 생각이 나지않아 숫자리스트를 구성한 뒤, 숫자가 리스트에 있으면 "*"을 붙이는 방식으로 하였습니다.

def change(input1):
    listb=[]
    listc=['1','2','3','4','5','6','7','8','9','0']
    for i in range(0,len(input1)):
        if i%2 !=0:
            if input1[i] in listc:
                listb.append("*")
            else:
                listb.append(input1[i])
        else:
            listb.append(input1[i])   
    return "".join(listb)

input1 ='a1b2cde3~g45hi6'
print change(input1)

2016/02/03 18:37

UNIST_BA

Ruby

convert = ->s{ s.chars.each_index.map{|i|i.odd?&&s[i].to_i>0?"*":s[i]}.join }

개선

convert = ->s{ s.chars.map.with_index{|v,i|i.odd?&&v.to_i>0?"*":v}.join }

Test

expect(convert["a1b2cde3~g45hi6"]).to eq "a*b*cde*~g4*hi6" # true

2016/02/04 12:18

rk

s = raw_input("input a string of numbers:")
ls = []
for i in s:
    ls.append(i)
for i in range(len(ls)):
    if i%2 != 0:
        ls[i] = "*"
print "".join(ls)

2016/02/17 16:35

취미로재미로

#coding: CP949

data=input('입력하라: ') # 문자 데이터 입력

data_list=list(data) # 문자를 리스트로 전환

i=1

while i<=len(data_list)-1: # while문은 짝수번째 문자에만 접근하여 *로 바꾸는 과정
    try:
        if type(int(data_list[i])) == type(1):
            data_list[i] = "*"
            i+=2
    except:
        i+=2
        continue

output="" 
for i in data_list: # data_list를 문자로 전환하여 출력
    output+=i
print(output)

파이썬 초짜 올려봐요~

2016/02/24 19:56

lovegalois2

python 3.5

def change_string(string):
    string = list(string)
    for x in range(len(string)):
        if x % 2 == 1 and string[x].isdigit():
            string[x] = '*'
    return ''.join(string)

print(change_string('a1b2cde3~g45hi6'))

2016/03/03 19:22

Lee Seul

void evenToStar(String s) {
        for(int i=0; i<s.length(); i++) {
            char index = s.charAt(i);
            if(i%2 == 1 && (int)index >= 48 && (int)index <= 57) {
                index = '*';
            }
            System.out.print(index);
        }
    }

java

2016/03/15 01:27

mozzi

일반:

while __name__ == '__main__':
    inpt = input('입력 ')
    print(''.join(list(inpt[x] if x%2 == 0 else '*' for x in range(len(inpt)))))

정규식:

import re

while __name__ == '__main__':
    inpt = input('입력: ')
    for x in re.compile('([^\*]).').finditer(inpt):inpt = inpt[:x.start()+1]+'*'+inpt[x.start()+2:]
    print(inpt)

2016/03/15 21:32

Flair Sizz

+1 첫번째에서 ''.join(list('*' if x % 2 != 0 and a[x].isnumeric() else a[x] for x in range(len(a)))) 이렇게 해야 될거같아요. 숫자일때의 조건이 없네요^^ - 디디, 2016/03/22 00:55

파이썬 3.4입니다.

a = 'a1b2cde3~g45hi6'

for i in range(len(a)):
    if i % 2 == 1 and a[i].isnumeric():
        print('*', end = '')
    else:
        print(a[i], end = '')

# 2016-10-27
print(''.join('*' if s[i].isdigit() and (i+1)%2==0 else s[i] for i in range(len(a))))

2016/03/22 00:47

디디

다음에 정규식으로도 풀어봐야겠네요, 지금은 이게 더 쉬운 듯한..

String input = "a1b2cde3~g45hi6";
        StringBuffer sb = new StringBuffer(input);
        for(int i = 0  ; i <input.length() ;i++){
            if(i%2 == 1 && (sb.charAt(i) >= '0' && sb.charAt(i)<='9') ) //짝수 번째
                sb.setCharAt(i, '*');
        }
        System.out.println(sb.toString());

2016/04/17 12:05

xeo

#파이썬3.5.1
def do(s):
    s = (' '.join(s)).split()
    for i in range(1,len(s),2):
        if s[i] in [str(x) for x in range(10)]:
            s[i] = '*'
    return ''.join(s)
print(do(input()))

2016/04/22 23:16

차우정

a="a1b2cde3~g45hi6"
for i in range(1,len(a),2):
    if a[i].isnumeric():
        a=a[:i]+"*"+a[i+1:]
print(a)

2016/04/28 02:04

Dr.Choi

python 3.4.4

data = list('a1b2cde3~g45hi6')

for i in range(1, len(data), 2):
    if data[i].isdigit():
        data[i] = '*'

print("".join(data))

2016/05/16 12:01

SanghoSeo

간단히 구현했는지 맞는지 모르겠네요

#include <stdio.h>
#include <string.h>
#pragma warning(disable:4996)
int main()
{
    char a[]="a1b2cde3~g45hi6";
    int size;

    size=strlen(a);

    for(int i=1;i<size;i+=2)
        if(a[i]>'/'&&a[i]<':') a[i]='*';

    printf("%s\n",a);
}

2016/05/24 03:40

유 종 근

words = "a1b2cde3~g45hi6"
for indexNum in range(len(words)-1):
    if 48 <= ord(words[indexNum]) <= 57:
        if indexNum % 2 == 1:
            words = words[:indexNum] + "*" + words[indexNum+1:]
print words

2016/08/05 13:19

kim

public class lv2_17 {
    public static void main(String[] args) {
        String str = "a1b2cde3~g45hi6";
        for(int i = 0 ;i < str.length();i++){
            if(str.charAt(i)>='0'&&str.charAt(i)<='9'&&i%2==1) System.out.print("*");
            else System.out.print(str.charAt(i));
        }
    }
}

2016/08/20 19:26

김준호

void exchanger(char *string)
{
    for (int i = 0; *(string + i) != NULL; i++)
        if (i % 2 == 1 & *(string + i) >= '0' & *(string + i) <= '9')
            *(string + i) = '*';
}

2016/10/13 01:05

김 진훈

string inputstr = "a1b2cde3~g45hi6";
string newstr = new String(inputstr.Select((k, i) => i % 2 != 0 && (k > 48 && k < 57) ? '*' : k).ToArray());
Console.WriteLine($"{inputstr} => {newstr}");

2016/11/23 15:50

lee jaekyoon

include

include

int main() { char str[256]; int i; fgets(str, sizeof(str), stdin); str[strlen(str)-1] = '\0'; for (i = 1; i < strlen(str); i+=2) { if ((str[i] < 48) || (str[i] > 57)) continue; str[i] = '*'; } printf("%s\n", str);

return 0;

}

2016/12/24 23:34

리코둔

def func(string):
    for x in range(1,len(string),2):
        if string[x].isnumeric():
            string = string[:x] + '*' + string[x+1:]
    return string

#### 2016.12.29 D-420 ####

2016/12/29 23:18

GunBang

#include  <stdio.h>
#include  <stdlib.h>
#include  <string.h>

void main() {
    char str[] = "a1b2cde3~g45hi6";

    for(int i=0;i<strlen(str);i++) {
        if((i+1)%2==0 && str[i] >= 48 && str[i] <= 57)
            str[i] = '*';
    }
    printf("%s", str);
}

2017/01/12 16:10

코딩초보

public class Test428 {

    public static void main(String[] args) {

        StringBuffer strb = new StringBuffer("a1b2cde3~g45hi6");
        for (int i = 1; i < strb.length(); i += 2) {
            if (isNumber(strb.charAt(i) + "")) {
                strb.setCharAt(i, '*');
            }
        }
        System.out.println(strb);
    }

    public static boolean isNumber(String num) {
        try {
            double d = Double.parseDouble(num);
        } catch (NumberFormatException nfe) {
            return false;
        }
        return true;
    }
}
a*b*cde*~g4*hi6

2017/02/13 12:09

김경수

def star(data):
    data=list(data)
    A="0123456789"
    return ''.join(['*' if i%2==1 and data[i] in A else data[i] for i in range(len(data))])
star("a1b2cde3~g45hi6")


2017/02/19 21:55

김구경

#include <iostream>
#include <string>

using namespace std;

int main()
{
    int strToNum, size; //strToNum: str의 문자를 정수형으로 변환한 값을 할당하기위한 변수, size: str의 사이즈를 저장하기위한 변수//
    string str = "a1b2cde3~g45hi6";
    size = str.size();
    cout << str << endl;
    for (int i = 0; i < size; i++) {
        strToNum = str.at(i);
        if (i % 2 != 0 && strToNum <= 57 && strToNum >= 48)
            str.at(i) = '*';
    }
    cout << str << endl;
    return 0;
}

2017/03/18 16:02

GyuHo Han

import java.util.Arrays;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/*
* URL : http://codingdojang.com/scode/428
* URL : http://docs.oracle.com/javase/8/docs/api/java/util/regex/Pattern.html Groups and capturing
* */
public class EveryOtherDigit {
    public static void main(String[] args) {
        String i = "a1b2cde3~g45hi6";
        String[] r = i.split("");
        Pattern p = Pattern.compile("\\d");
        Matcher m = p.matcher(i);
        while (m.find()) {
            if (m.start() % 2 != 0) r[m.start()] = "*";
        }
        System.out.println(String.join("", Arrays.asList(r)));
    }
}

2017/03/27 17:27

genius.choi

def eod(s):
    return ''.join(['*' if (i+1) % 2 == 0 and '0' <= s[i] <= '9' else s[i] for i in range(len(s))])

print(eod('a1b2cde3~g45hi6'))

2017/04/09 17:20

soleaf

package training;

/**
 * 모든 짝수번째 숫자를 * 로 치환하시오.(홀수번째 숫자,또는 짝수번째 문자를 치환하면 안됩니다.) 
 * Example: a1b2cde3~g45hi6 → a*b*cde*~g4*hi6
 */
public class EveryOtherDigit {
    public static void main(String[] args) {
        String str = "a1b2cde3~g45hi6";
        char[] ch = str.toCharArray();
        StringBuffer sf = new StringBuffer();

        for(int i=0;i<ch.length;i++){
            if((i+1)%2 == 0){ // 짝수일 경우
                if(ch[i] == '0' || ch[i] == '1' || ch[i] == '2' || ch[i] == '3' || ch[i] == '4'
                || ch[i] == '5'|| ch[i] == '6' || ch[i] == '7' || ch[i] == '8' || ch[i] == '9')
                {
                    sf.append("*");
                } else {
                    sf.append(ch[i]);
                }
            } else { // 홀수일 경우
                sf.append(ch[i]);
            }
        }
        System.out.println(sf);
    }
}

2017/04/16 14:22

acedo

y=list("a1b2cde3~g45hi6")

for i in range(len(y)):
    if (i-1)%2==0 and y[i].isdigit()==True :
        y[i]="*"
result="".join(y)

print(result)

2017/05/15 10:56

정세진

var input = "a1b2cde3~g45hi6";

// regular expression with callback
var result = input => input.replace(/.\D|.(\d)/g, (s,d) => d ? s[0] + "*" : s);

console.log(result1(input));

2017/06/19 09:47

funnystyle

정규표현식으로 잘 안풀리네요;; 풀이를 보기 전에 단순한 방법으로 작성한 코드를 올립니다.

def replace_even_number(s):
    new_s = ''
    for i in range(0, len(s)):
        if i % 2 is not 0 and s[i].isdigit():
            new_s += '*'
        else:
            new_s += s[i]
    return new_s

정규표현식으로 풀었습니다. 'aa1'과 같은 경우에는 변경이 없어야 합니다.

2칸씩 match하면서 '그룹2'가 있으면 ('그룹1' + '그룹2')로, 없으면 ('그룹1' + '*')로 변환합니다.

import re
def replace_even_number(s):
    repl=lambda m: m.group(1) + (m.group(2) if m.group(2) else '*')
    return re.sub(r'(.)(?:\d|(\D))', repl, s)

2017/07/11 13:44

SOUP

정규표현식 잘 배우고 갑니다 - 빗나감, 2017/12/14 23:47
def numtosc(string) :

    listedstring = list(string)
    number_list = []

    for i in range(0, 10):
        number_list.append(str(i))

    for n in range(1, len(string), 2) :
        if listedstring[n] in number_list :
            listedstring[n] = '*'

    return ''.join(listedstring)


string_input = input("any string with alphabet, number, and special characters : ")
print(numtosc(string_input))

2017/07/31 22:10

다크엔젤

import re

print(re.sub(f'(\D*?\d\D*?)(\d)', '\g<1>*', 'a1b2cde3~g45hi6 → a*b*cde*~g4*hi6'))

2017/08/22 23:48

Noname

def changeNum(str):
    for idx, chr in enumerate(str):
        if (idx+1)%2 == 0 and chr.isdigit():
            str = str.replace(chr, '*', 1)
    print(str)



changeNum('a1b2cde3~g45hi6')

2017/08/23 10:34

piko


/**
 * @author : 염현우
 * @date :2017. 9. 8.
 * @description : 
 * 모든 짝수번째 숫자를 * 로 치환하시오.(홀수번째 숫자,또는 짝수번째 문자를 치환하면 안됩니다.) 
 * 로직을 이용하면 쉬운데 정규식으로는 어려울거 같아요.
 * Example: a1b2cde3~g45hi6 → a*b*cde*~g4*hi6
 * 
 */

public class Ex9 {
    public static void main(String[] args) {

        String data = "a1b2cde3~g45hi6";
        StringBuilder result = new StringBuilder();
        for(int i=0;i<data.length();i++) {
            if(i%2 == 0) { 
                result.append(data.charAt(i));
                continue;
            }

            if(Character.isDigit(data.charAt(i)))   result.append("*"); 
            else result.append(data.charAt(i));
        }

        System.out.println(result);

    }
}

2017/09/08 17:40

염현우

package codingdojang;

import java.util.Scanner;

public class ex41 {

public static void main(String[] args) {
    // TODO Auto-generated method stub
    Scanner sc = new Scanner(System.in);

    String temp = sc.nextLine();
    int count = 0;
    boolean num = false;
    char arr[] = temp.toCharArray();

    for(int i=0; i < arr.length; i++) {
        num = false;
        if('0' <= arr[i] && arr[i] <= '9') {
            count++;
            num = true;
        }
        if(count%2==0 && num == true) {
            arr[i] = '*';
        }
    }

    System.out.println(arr);
}

}

2017/10/10 14:28

이병호

char = "a1b2cde3~g45hi6"
new=""
i=0
for ch in char :
    i +=1
    if i%2==0 and ch.isdigit(): ch = "*"
    new = new + ch
new

python 3.5.2 입니다.

2017/11/18 07:49

Seohyun Choi

import re
a = raw_input("enter something: ")
p = re.compile('\d')
c = []
for i in range(len(a)):
    m = p.match(a[i])
    if (i+1) % 2 == 0 and m:
        c.append("*")
    else:
        c.append(a[i])
print "".join(c)

2017/12/06 04:57

영이

sen=input()
for x,y in enumerate(sen[1::2]):
    if y.isdigit():
        sen=sen[:x*2+1]+'*'+sen[x*2+2:]
print(sen)

2017/12/14 23:19

빗나감

txt = list('a1b2cde3~g45hi6')
for i in range(0,len(txt),2):  # 짝수만 받아오기 !!
    if  txt[i].isnumeric():
        txt[i]='*'
print("".join(txt))

2017/12/17 15:57

얏홍

txt = list('a1b2cde3~g45hi6')
for i in range(0,len(txt),2):  # 짝수만 받아오기 !!
    if  txt[i].isnumeric():
        txt[i]='*'
print("".join(txt))

2017/12/17 15:58

얏홍

파이썬 3.6

data = 'a1b2cde3~g45hi6'

def change_even(data):
    datalist = list(data)
    for i, value in enumerate(datalist):
        if (i+1)%2 == 0 and value.isdigit():
                datalist[i] = '*'

    print(data," -> ",''.join(datalist),"\n")

if __name__ == "__main__":
    change_even(data)

*결과값

a1b2cde3~g45hi6  ->  a*b*cde*~g4*hi6

2018/01/07 13:56

justbegin

# 파이썬

sample = "a1b2cde3~g45hi6"


def eod(str1):
    n = 0
    r = ""
    for m in str1:
        if n == 0:
            n = 1
            r += m
        elif n == 1:
            n = 0
            if m in "1234567890":
                r += "*"
    return r


print(eod(sample))

2018/02/07 00:35

olclocr

def evendigit(n):
    a = list(n)
    for i in range(len(a)//2):
        if a[2*i+1] in '0123456789':
            a[2*i+1] = '*'
    b = ''
    for i in a:
        b += i
    return b


m = input()
print(evendigit(m))

2018/02/08 15:40

김동하

import java.util.*;

public class Main { public static void main(String[] args) { Scanner scanf=new Scanner(System.in); String s=scanf.next();

    char[] chr=s.toCharArray();
    StringBuffer sb=new StringBuffer();

    for(int i=1; i<chr.length; i=i+2) {
        if(Character.isDigit(chr[i])) {
            chr[i]='*';
        }

    }
    for(int i=0; i<chr.length; i++) {
        System.out.print(chr[i]);
    }


}

}```{.java}

```

2018/02/14 01:36

즈스크

for_change_string=input("바꾸려는 문자열을 입력하세요\n")

len_for_change_string=len(for_change_string)
new_str=''

for k in range(len_for_change_string):
    if k%2==1 and for_change_string[k].isdigit():
        new_str+='*'
    else:
        new_str+=for_change_string[k]

print(new_str)

2018/02/18 19:52

D B

import re

def digit(string) :

    p = re.compile('\d')
    str_list = re.findall('.', string)

    for i in range(1, len(str_list), 2) :
        str_list[i] = p.sub('*', string[i])

    print(''.join(str_list))

정규식으로 풀어봤습니다. 패턴객체를 if 조건처럼 활용해서 풀어봤어요.

2018/03/08 15:35

박강민

def change(put):
    result = ''
    for n, char in enumerate(put):
        if n%2 == 1:
            try:
                if int(char)*1 == int(char):
                    result = result + '*'
            except: result = result + char
        else: result = result + char
    return result

Python 3

2018/03/22 23:48

myyh2357

s = input("input: ")
n_s = []
for i in range(0,len(s)):
    if i % 2 == 1:
        if s[i] in '0123456789':
            n_s.append('*')
        else:
            n_s.append(s[i])
    else:
        n_s.append(s[i])
print("".join(n_s))

2018/03/23 23:37

정익수

import java.util.Scanner;
import java.util.regex.Pattern;

public class EveryOtherDigit {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        Scanner sc = new Scanner(System.in);

        String input = sc.nextLine();

        StringBuilder sb = new StringBuilder(input);

        Pattern p = Pattern.compile("[0-9]");

        for(int i=1; i< sb.length(); i=i+2){
            if(p.matcher(sb.substring(i, i+1)).find()){
                sb.replace(i, i+1, "*");
            }
        }
        System.out.println(sb.toString());
    }

}

2018/04/06 17:46

김태훈

Swift입니다. 정규식 없이 풀었습니다.

import Foundation

func translate(_ input: String) -> String {
    var inputArray = Array(input)
    for i in stride(from:1, to: inputArray.count, by: 2) {
        if "0"..."9" ~= inputArray[i] {
            inputArray[i] = "*"
        }
    }
    return String(inputArray)
}


print( translate("a1b2cde3~g45hi6") )

2018/04/10 07:08

졸린하마

// Every Other Digit
package main

import (
    "fmt"
    "strconv"
)

// cnvt: aString의 짝수번째 문자가 숫자일 경우 *로 치
func cnvt(aString string) string {
    newString := ""
    for i, v := range aString {
        if _, err := strconv.Atoi(string(v)); i%2 == 1 && err == nil {
            newString += "*"
        } else {
            newString += string(v)
        }
    }
    return newString
}

func main() {
    inpString := "a1b2cde3~g45hi6"
    fmt.Println(cnvt(inpString))
}

2018/04/10 10:49

mohenjo


def star(str):
    for i in range(len(str)):
        if i % 2 == 1 and str[i].isnumeric() == True:
            str = str.replace(str[i],"*")
    return str


print(star("a1b2cde3~g45hi6"))

2018/04/17 16:16

yijeong

import java.util.Scanner;

public class Dig{
 public static void main(String[] args){
  Scanner sc = new Scanner(System.in);
  String exaMple = sc.nextLine();

  System.out.println("String 입력");

  String arr[] = new String [exaMple.length()];

  for(int i=0;i<exaMple.length();i++){
   arr[i] = exaMple.charAt(i) + "";
   if(Character.isDigit(exaMple.charAt(i)) && exaMple.indexOf(exaMple.charAt(i))%2!=0)
    arr[i] = "*";
   System.out.print(arr[i]);
  }
   System.out.println();
 }
}

2018/04/25 20:18

배혜민

//자바입니다
 public static void main(String[] args) throws Exception { 
        String str = "a1b2cde3~g45hi6";
        StringBuffer sb = new StringBuffer(str);
        for (int i=0; i<sb.length(); i++) {
            if (i%2 == 1 && (48 <=sb.charAt(i) && sb.charAt(i) <= 57)) {
                sb.setCharAt(i,'*');
            }
        }
        System.out.println(sb);
    } // 스트링버퍼의 메서드를 썻어요

2018/05/05 13:47

정몽준

user_input = input()

def Change_String(string):

    result = ''

    for index in range(len(string)):

        if index % 2 == 0  :
            result = result + string[index]

        elif index %2 == 1 and not string[index].isnumeric():
            result = result + string[index]

        else:
            if string[index].isnumeric():
                result = result + '*'

    return result

print(Change_String(user_input)) # a*b*cde*~g4*hi6

2018/05/06 11:58

최우성

public class substitute implements baseInterface {

    @Override
    public void init() {


        System.out.println("아무 문제나 입력 : ");

        Scanner sc = new Scanner(System.in);

        String str = sc.nextLine();

        System.out.println(str);

        char[] temp = new char[100];


        int lengthStr = str.length();

        for (int i = 0; i < lengthStr; i++) {
            char c = str.charAt(i);

            temp[i] = c;

            if((i+1)%2 == 0){

                if(c<48 || c> 57){ // 문자인 경우
                    temp[i] = '*';
                }
            }       

        }

        str = "";

        for (int i = 0; i < lengthStr; i++) {
            str += temp[i];

        }

        System.out.print(str);




    }

}

2018/05/14 15:48

聂金鹏


public class EveryOtherDigit {
    public static void main(String[] args) {
        String str = "a1b2cde3~g45hi6";
        for (int i = 1; i < str.length(); i += 2)
            if (str.substring(i, i + 1).matches("^[0-9]$"))
                str = str.replaceAll(str.substring(i, i + 1), "*");
        System.out.println(str);
    }
}

2018/06/01 20:57

김지훈

Python

test = "a1b2cde3~g45hi6"
ans = ""
for i, c in enumerate(test):
    if (i+1)%2 == 0 and c.isdigit():#even index
        ans += "*"
    else:
        ans += c
print(ans)


2018/06/04 16:47

Taesoo Kim

// 코딩연습
#include <stdio.h>

int main() {
    char str[100];
    scanf("%s",str);

    for(int i=0; str[i]; i++) {
        if(str[i]>='0' && str[i]<='9' && (i+1)%2==0) {
            str[i]='*';
        }
    } 
    printf("%s\n",str);
}

2018/06/16 14:28

gudrhrehd123

a = "a1b2cde3~g45hi6"
print(''.join(['*' if (a[i].isdigit() and (i+1)%2 == 0) else a[i] for i in range(len(a))]))



import re
repl = lambda m: m.group(1) + (m.group(2) if m.group(2) else '*')
print(re.sub(r'(.)(?:\d|(\D))', repl, a))

2018/06/30 10:37

재즐보프

s = 'a1b2cde3~g45hi6'
print(''.join('*' if i%2 and s[i].isdigit() else s[i]  for i in range(len(s))))
import re
s = 'a1b2cde3~g45hi6'
print(re.sub('((..)+?)(.)\d',r'\1\3*',re.sub('(^(..)*?)(.)\d',r'\1\3*',s)))

2018/07/08 18:01

Creator

파이썬3

def fn(s):
    result = ""
    digits = "0123456789"
    for i, v in enumerate(s):
        if i % 2 == 1 and v in digits:
            result += "*"
        else:
            result += v
    return result


input = "a1b2cde3~g45hi6"
print(fn(input))

결과

a*b*cde*~g4*hi6

2018/07/13 20:54

WJ K

import re

su=re.compile("\d") #숫자일경우
mun=re.compile("\D")#숫자가 아닐경우

data = 'a1b2cde3~g45hi6'
count =1
result = []
result2 =""
for i in data:
    if count%2 ==1: #홀수번째
        result.append(i)
    elif count%2 ==0:#짝수번째
        if su.match(i):#숫자일경우
            i='*'
            result.append(i)
        elif mun.match(i): #문자일경우
            result.append(i)
    count+=1
for y in range(len(result)): #리스트 ->문자열
    result2 += result[y]

print(result2)

2018/07/15 15:32

S.H

#모든 짝수번째 숫자를 *로 치환하시오

def change (x):
    x=list(x)
    for i in range(1,len(x),2):
        if x[i].isdigit()==True:
            x[i]='*'

        else:
            pass

    return ''.join(x)






print(change('12415123412341234512'))


2018/08/08 12:48

IN K

C언어
#include<stdio.h>
#include<string.h>

int main()
{
    char example[]="a1b2cde3~g45hi6";
    int len;
    int i;

    len = strlen(example);

    for(i=1; i<len; i=i+2)
    {
        if('9'>=example[i] && '0'<=example[i])
        {
            example[i] = '*';
        }
    } 

    for(i=0; i<len; i++)
    {
        printf("%c",example[i]);
    }
}

2018/08/12 20:26

이우경

def evennum(n):
     n = list(n)
     for x in n:
          if x.isdigit() and (n.index(x)+1)%2 == 0:
               n[n.index(x)] = '*'
     print(''.join(n))

2018/08/14 20:29

김영성

def e(a):
    l = list(a)
    for i in range(1, len(a), 2):
        if l[i].isdigit(): l[i] = '*'
    return ''.join(l)

2018/08/24 13:15

김건우

def fix(arr):
    l = list(arr)
    for i in range(len(l)):
        if i % 2 == 1 and '0' < arr[i] < '9':
            l[i] = '*'
    print (''.join(l))

test = 'a1b2cde3~g45hi6'

fix(test)

2018/08/27 01:35

Wisp

C#

using System;
using System.Linq;

namespace CD041
{
    class Program
    {
        static void Main()
        {
            string input = "a1b2cde3~g45hi6";
            string result = new String(input.Select((v, i) => (i % 2 == 1 && Char.IsDigit(v)) ? '*' : v).ToArray());
            Console.WriteLine(result);
        }
    }
}

2018/09/06 15:26

mohenjo

s = 'a1b2cde3~g45hi6'
result = ''
for idx, i in enumerate(s):
    if idx%2!=0:
        if i.isdigit():
            result = result + '*'
        else:
            result = result + i            
    else:
        result = result + i

print(result)

2018/10/30 14:57

Dae Su Jeong

import java.util.Scanner;

public class KimSanghyeop {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        Scanner sc = new Scanner(System.in);
        System.out.print("문장을 입력하세요 : ");
        String str = sc.nextLine();
        char[] arr = str.toCharArray();

        String res = "";
        for(int f1=0;f1<arr.length;f1++)
        {

            if(f1 % 2 ==1  && arr[f1] >= '0' && arr[f1] <='9')
            {
                res+="*";
            }
            else
            {
                res+=arr[f1];
            }
        }

        System.out.println(res);

    }
}

2018/12/21 00:11

김상협

def even_num_to_star(s):
    l = list(s)
    for i in range(1, len(l), 2):
        if l[i].isdigit():
            l[i] = '*'

    return ''.join(l)

2019/01/11 18:16

Gerrad kim

c언어 입니다.

include

include

include

int main() { char a= malloc(sizeof(char)254); strcpy(a, "a1b2cde3~g45hi6"); int size=strlen(a);

for(int i=0;i<size;i++){
    if(i%2==1){
        if(a[i]>=48 && a[i]<=57){
            a[i]='*';
        }
    }
}
printf("%s", a);

}

2019/01/19 23:24

이호석

string = input()
for i in string:
    if i.isdigit() and string.find(i) % 2 != 0:
        string = string.replace(i,'*')
print(string)

2019/01/25 15:41

D.H.

example = "a1b2cde3~g45hi6"

#a*b*cde*~g4*hi6

answer = list(example)
for idx in range(1,len(example),2):
    if example[idx].isdigit():
        answer[idx]="*"
print(''.join(answer))

2019/01/29 09:56

임정섭

ex = 'a1b2cde3~g45hi6'
out = ''
for i, ch in enumerate(ex):
    if 0 != i % 2 and '0' <= ch and '9' >= ch:
        out += '*'
    else:
        out += ch
print(out)

2019/02/01 22:00

Roy

function change(input){
  const splitted = input.split('')
  const result = splitted.map((split,index)=>isNaN(Number(split))===false && index%2 ===1?split = '*':split = split)
  return result.join('')
}

change('a1b2cde3~g45hi6')

2019/02/15 21:34

돌도끼

in_str = input("입력: ")

for i in range(2,len(in_str),2):
    if ord(in_str[i-1])>47 and ord(in_str[i-1])<58:
        in_str = in_str[:i-1]+'*'+in_str[i:]
print(in_str)

2019/02/18 15:35

a=list(input())
for x in range(len(a)):
    if x%2==1:
        try:
            float(a[x])
            a[x]='*'
        except:
            pass
    else:
        pass
print(''.join(a))

2019/02/21 16:04

소요자재

namespace codingdojang__
{
    class Program
    {
        static void Main(string[] args)
        {
            Every_other_digit("a1b2cde3~g45hi6");
        }
        static void Every_other_digit(string input)
        {
            int temp;
            for (int i = 0; i < input.Length; i++)
            {
                if ((i + 1) % 2 == 0 && int.TryParse(input[i].ToString(), out temp) == true)
                {
                    input = input.Insert(i, "*");
                    input = input.Remove(i + 1, 1);
                }
            }
            Console.WriteLine(input);
        }
    }
}

2019/02/25 14:40

bat

number='1234567890'
user=input("Input string: ")
for i in range(len(user)):
    if i%2==1 and user[i] in number:
        user=user[:i]+"*"+user[i+1:]

print(user)

2019/03/02 19:43

ykleeac

def every_other_digit(string):
  new = ""
  for n, s in enumerate(string):

    if (n+1) % 2 == 1:
      new += s
    if (n+1) % 2 == 0:
      if s in "0123456789":
        new += "*"
      else:
        new += s
  print(new)

2019/03/06 18:03

그사람 남한 볼 수 있어요

str=input("영어와 숫자를 입력하시오:")
sum=0
str_pos=[]
new_str=""
for x in str:
    sum+=1
    str_pos.append(x)
for x in range(0,sum):
    if x%2==1:
        if ord(str_pos[x])>=47 and ord(str_pos[x])<=59:
            str_pos[x]='*'
for x in range(0,sum):
    new_str+=str_pos[x]
print(new_str)

2019/03/28 01:27

빅디펜스

import java.util.Scanner;

public class EveryOtherDigit {
    public static void main(String[] args) {

        Scanner scanner = new Scanner(System.in);
        System.out.println("문자를 입력하세요.");
        String str = scanner.nextLine();

        for(int i = 1; i < str.length(); i += 2) {

            if(isnumber(str.substring(i, i + 1))) {
                System.out.print(str.substring(i, i + 1) + " ");
            }
        }

    }
    public static boolean isnumber(String string) {
        boolean result = false;

        try {
            Integer.parseInt(string);
            result = true;
        } catch (Exception e) { }

        return result;
    }
}

2019/04/05 17:15

김동혁

def chihwan(string):
    lst = []
    for ind_i,i in enumerate(string):
        if ind_i % 2 == 1 and i in ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']:
            lst.append('*')
        else:
            lst.append(i)
    return ''.join(lst)

2019/04/06 17:11

dodoman

a = 'a1b2cde3~g45hi6'
a = list(a)
res=''

for i in range(1,len(a),2):
    if a[i] in '0123456789':
        a[i]='*'
for j in a:
    res += str(j)

print(res)

2019/04/16 11:33

Chang Hwan Kim

def f(s):
    for i in range(1, len(s), 2):
        if s[i] in '0123456789':
            s = s[:i] + '*' + s[i+1:]
    print(s)

2019/05/01 16:18

messi

s=input();ans=''

for i in range(len(s)):
    if ord('0')<=ord(s[i])<=ord('9'):
        if (i+1)%2==0:
            ans+='*'
        else:
            ans+=s[i]
    else:
        ans+=s[i]

print(ans)

2019/05/04 12:50

암살자까마귀

a=input("문자열입력: ")
num=['0','1','2','3','4','5','6','7','8','9']
b=""
for i in a:
    if a.index(i)%2==1 and i in num:
        b=b+'*'
    else:
        b=b+i
print(b)

2019/08/18 19:43

박재욱

PHP

$str = 'a1b2cde3~g45hi6';
$arr = str_split($str);
foreach ($arr as $k => & $v) {
    if ($k % 2) $v = preg_replace("/\d/", "*", $v);
}
$result = implode($arr);
print_r($result); // a*b*cde*~g4*hi6

2019/09/11 16:33

d124412

def convert(str):
    a = '0123456789'
    lstStr = list(str)
    for i in range(len(lstStr)):
        if i % 2 == 1 and lstStr[i] in a:
            lstStr[i] = '*'
    return ''.join(lstStr)

print(convert('a1b2cde3~g45hi6'))

2019/09/25 14:48

Dreaming Pug

txt = "a1b2cde3~g45hi6"

for i in range(1,len(txt),2):
    if 48 <= ord(txt[i]) <= 57 :
        print(ord(txt[i]))
        txt = txt[:i] + "*" + txt[i+1:]
print(txt)

2019/10/28 22:26

semipooh

python3

NUM = [str(i) for i in range(0, 10)]

def function(data):
  out = ''
  for i in range(0, len(data)):
    if data[i] in NUM and (i+1)%2 == 0:
      out += '*'
    else:
      out += data[i]
  return out

data = 'a1b2cde3~g45hi6'
out = function(data)
print(out)

2019/10/29 19:41

조현우

import java.util.*;
public class EveryOtherDigit {

    public static void main(String[] args) {

        Scanner scan = new Scanner(System.in);
        String[] strs = scan.next().split("");
        ArrayList<String> list = new ArrayList<String>();
        for(int i=0; i<strs.length; i++) {
            list.add(strs[i]);
        }
        for(int j=1; j<strs.length; j=j+2) {
            try {
                Integer.parseInt(strs[j]);
                list.set(j, "*");
            }
            catch(NumberFormatException e){
            }
        }
        String line = String.join("", list);//string arraylist를 변환하는 경우
        System.out.println(line);
    }
}

2019/11/17 20:36

big Ko

#include <iostream>
using namespace std;

char a[100];

int main(){
    int n;
    cin>>n;

    for(int i=1;i<=n;i++)
        cin>>a[i];

    for(int i=1;i<=n;i++)
        if(i%2==0)
            if(a[i]>=48 && a[i]<=57)
                a[i]='*';

    for(int i=1;i<=n;i++)
        cout<<a[i];
}

2019/11/23 11:50

저택벚꽃

파이썬 3.6 입니다

def replace_even_index_numbers(s):
    s_list = list(s)
    rst = []
    for i in range(1, len(s_list), 2):
        if s_list[i].isnumeric():
            s_list[i] = "*"
    return "".join(s_list)

print(replace_even_index_numbers("a1b2cde3~g45hi6"))

2019/12/04 19:29

vkospi

def digit(x):
    y =list(x)
    for i in range(1,len(y),2):
        if y[i].isdigit():
            y[i]='*'
    return ''.join(y)
print(digit('a1b2cde3'))

2020/01/04 14:55

뚜루꾸까까

st=list(map(str,input("문자열을 입력하십시오: ")))
for i in range(len(st)):
    if i%2!=0 and st[i].isdigit() is True:
        st[i]="*"
print("".join(st))

2020/01/27 17:04

박시원

is True는 지우셔도 될 듯합니다. True, False값이 1,0입니다. - mr. gimp, 2020/03/07 19:14

재귀함수를 이용해서 값을 판별하는 방법과 반복문을 통해서 값을 판별하는 방법 이 2가지로 풀었습니다.

import java.util.Scanner;

public class DigitConverter {
    public static void main(String[] args) {
        int i = 0;

        Scanner sc = new Scanner(System.in);
        DigitConverter dc = new DigitConverter();

        System.out.print("문자열을 입력하시오: ");
        String str = sc.nextLine();
        char[] array = dc.Swap(str);
        dc.Converter1(array, i);
        dc.Converter2(array);
        sc.close();

    }
    //char[]에 값 저장하는 메소드
    public char[] Swap(String str) {                    
        char[] array = new char[str.length()+1];
        for(int i = 0; i<str.length(); i++) {
            array[i] = str.charAt(i);
        }
        array[str.length()]= '\0';                  //char[] 마지막에 \0값 넣기
        return array;
    }
    //재귀함수를 이용하여 값 판별하는 메소드
    public void Converter1(char[] array , int i) {      
        if(array[i]=='\0') {                        //char[] 마지막일떄 메소드 종료
            System.out.println();
            return;
        }
        if((i%2==1) && (array[i]>= '0') && (array[i]<= '9')) {  //짝수번째 숫자 *로 치환
            array[i] = '*';
        }
        System.out.print(array[i]);
        Converter1(array, i+1); 
    }
    //반복문을 이용하여 값을 판별하는 메소드
    public void Converter2(char[] array) {
        for(int i =0; i<array.length; i++) {
            if((i%2==1) && (array[i]>= '0') && (array[i]<= '9')) {  //짝수번째 숫자 *로 치환
            array[i] = '*';
            }
            System.out.print(array[i]);
        }
        System.out.println();
    }
}

2020/02/11 00:55

김강민

import re

def main(inp) :
    inp_ev = inp[1::2]
    EOD_com  = re.compile("\d")
    inp_ev = EOD_com.sub('*', inp_ev)
    for i in range(0, len(inp_ev)) :
        inp = inp.replace(inp[2*i+1], inp_ev[i])
    return inp

if __name__ == '__main__' :
    print(main(input("INPUT : ")))

먼저 입력된 문자열의 짝수번째만 따로 모은 뒤, 정규식으로 숫자만 *로 바꿔서 다시 문자열에 돌려놓았습니다.

결과

INPUT : a1b2cde3~g45hi6
a*b*cde*~g4*hi6

2020/02/11 16:12

GG

N = list(input("Example: "))
for i in range(1,len(N)):
    if i % 2 != 0:
        try:
            int(N[i])
            N[i] = '*'
        except ValueError:
            pass
finish = ""
for i in range(len(N)):
    finish += N[i]
print("→ ",finish)

2020/02/11 23:49

BlakeLee

def subs(n):
    val=''
    ln=[]
    nd=[]
    nl=[]
    for i in range(len(n)):
        ln.append(n[i])
    for i in range(int(len(n)/2)):
        try:
            nd.append(n[i*2+1])
            nd[i]=int(nd[i])
            nl.append(i*2+1)
        except:
            pass
    for i in range(len(nl)):
        del ln[int(nl[i])]
        ln.insert(nl[i],'*')
    for i in range(len(ln)):
        val+=ln[i]
    print(val)

subs(input())

2020/03/01 19:33

Shiroha

def subs():
        input_string = input("문자열: ")
        input_list = list(input_string)
        for i in range(0, len(input_list)):
                if i % 2 == 1:
                        input_list[i] = "*"
        i += 1
        result = "".join(input_list)
        return result

2020/03/01 23:39

PythonLover&Master_JK73

python 3.8

a='a1b2cde3~g45hi6'

for i in range(len(a)) :
  print("*" if (a[i]).isnumeric() and i&1 else a[i],end='')
  
# 3항 연산자를 이용, i&1은 홀수와 짝수를 결정 isdigit()도 동일한 결과 출력
 end=''는 가로 방향 연속 출력을 위해 입력됨.

이 문제에 대한 상파님의 아이디어를 활용하여 윗식을 아래식으로 교체해보았습니다.

for i in range(len(a)):
    print([a[i],'*'][i&1 and a[i].isdigit()],end='')

2020/03/06 22:00

mr. gimp

l = list(input())

for k in range(1, len(l), 2):

    if l[k].isdigit():

        l[k] = '*'

print (''.join(l))

2020/03/10 09:12

HyukHoon Kim

#include <iostream>
#include <string>
using namespace std;
/*
모든 짝수번째 숫자를 * 로 치환하시오.
(홀수번째 숫자,또는 짝수번째 문자를 치환하면 안됩니다.) 로직을 이용하면 쉬운데 정규식으로는 어려울거 같아요.

Example: a1b2cde3~g45hi6 → a*b*cde*~g4*hi6
*/

void Func(string s) {
    cout << s << " -> ";
    int n;
    for (int i = 0; i < s.length(); i++) {
        if ((i + 1) % 2 == 0) {
            n = s[i] - '0';
            for (int j = 0; j <= 9; j++) {
                if (n == j) { s[i] = '*'; }
            }
        }
    }
    cout << s << endl;
}

int main() {
    Func("a1b2cde3~g45hi6");
}

2020/03/21 17:57

++C

a = list(input("입력: "))

for i in range(1, len(a), 2):
    if a[i].isdigit()== True:
        a[i] = "*"

print("".join(a))



2020/03/23 23:15

김희준

# 파이썬

a=str(input('숫자 및 문자를 입력해주세요....'))
for i in range (0,len(a)):
    if i%2!=0 and (ord(a[i])>=48 and ord(a[i])<=57): #짝수번째 숫자를 치환하라고 했으나 리스트에서는 짝수번째가 홀수번째임
        print ('*',end='')
    else:
        print (a[i],end='')

2020/04/08 14:07

Buckshot

<결과> 숫자 및 문자를 입력해주세요....a1b2cde3~g45hi6 a*b*cde*~g4*hi6 - Buckshot, 2020/04/08 14:08
s = 'a1b2cde3~g45hi6'
print(''.join(['*' if (i % 2 == 1) and (s[i].isdigit()) else s[i] for i in range(len(s))]))

2020/04/15 13:11

Hwaseong Nam

cur=list(input("Example: "))
for i in range(len(cur)):
    if (i+1)%2==0 and cur[i]>='1' and cur[i]<'9':
        cur[i]="*"
Str=""
for i in range(len(cur)):
    Str+=cur[i]

print(Str)

2020/04/24 22:31

kim center

st=input('문자숫자 섞어서 ....  : ')
for i in range(len(st)):
    try:
        if int(st[i])%2==0:
            if i%2==0:
                st=st.replace(st[i],'*')
            else:pass
        else:
            pass
    except:
        pass


print(st)

2020/04/28 23:39

양양짹짹

def convert_even_digit(s):
    convert = lambda i: "*" if i % 2 != 0 and s[i].isdigit() else s[i]
    return "".join([convert(i) for i in range(len(s))])

2020/05/08 22:04

김준혁

Example = list(input())
for i in range(1, len(Example), 2):
    if Example[i].isdigit():
        Example[i] = '*'
print(Example)

2020/05/11 22:46

Money_Coding

a=list(input())
b=[]
for i in range(0,len(a)):
    try:
        if i%2==0:
            b.append(a[i])
        elif i%2!=0 and int(a[i]):
            b.append('*')
    except:
        b.append(a[i])

print(''.join(b))

2020/06/18 11:05

SREBP1c

파이썬3입니다.

a = list(input('type any words.'))
b = ['*' if a.index(x) % 2 == 1 and x.isdigit() else x for x in a]
print(''.join(b))

2020/06/18 15:00

누마루

char인 숫자를 int로 변환하면 어떻게 되는지 배웠다!


import java.util.ArrayList;
import java.util.Scanner;

//모든 짝수번째 숫자를 * 로 치환하시오.(홀수번째 숫자,또는 짝수번째 문자를 치환하면 안됩니다.)
//Example: a1b2cde3~g45hi6 → a*b*cde*~g4*hi6
//아스키 코드에 대해 배움 1~9 → 49~57

public class main {

    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        String a = scan.nextLine();

        char[] list = a.toCharArray();

        for(int i=0;i<list.length;i++)
        {
            if(i%2==1)
            {
                if((int)list[i]>48 && (int)list[i]<58)
                System.out.print("*");
            else
                System.out.print(list[i]);
            }
            else
                System.out.print(list[i]);
        }
        }
    }

2020/07/22 00:49

허병우

a = input("Enter: ")

def Digit_word(word):
    W=[x for x in word]
    p=""
    for i in range(len(W)):
        if i%2!=0:
            if W[i].isnumeric():
                W[i]="*"
        p+=W[i]
    print(p)

Digit_word(a)

2020/07/29 21:10

김병관

package test;

public class Test{
     public static void main(String args[]) {
         String a = "a1b2cde3~g45hi6";
         for(int i=0; i< a.length(); i++) {
             if(a.indexOf(a.charAt(i)) % 2 == 1 && Character.getNumericValue(a.charAt(i)) < 10) {
                 System.out.print('*');
             }
             else{System.out.print(a.charAt(i));}
         }
    }
}

2020/08/21 16:58

들산

print(''.join([inp[i],'*'][i&1 and inp[i].isdigit()] for i in range(len(inp))))

2020/09/09 10:18

Bbb Aaa

public class test13 {
    public static void main(String[] args) {
        String input = "a1b2cde3~g45hi6";
        StringBuffer buffer = new StringBuffer(input);

        for(int i = 0; i < buffer.length(); i++) {
            if(i % 2 == 1) {
                buffer.setCharAt(i,isParsable(buffer.charAt(i)));
            }
        }
        System.out.println(buffer);
    }

    public static char isParsable(char input) {
        try {
            Integer.parseInt(String.valueOf(input));
            return '*';
        } catch (final NumberFormatException e) {
            return input;
        }
    }
}

2020/09/16 16:43

nazunamoe

s = "a1b2cde3~g45hi6"
result = ""
for i in range(0, len(s)):
    if i % 2 == 1 and s[i].isdigit():
        result += "*"
    else:
        result += s[i]
print(result)

2020/11/24 16:14

김우석

#55 Level 2 : https://codingdojang.com/scode/428

def digit(text):
    temp = list(text)
    # result = []
    for i in range(1, len(temp), 2):
        if temp[i].isdigit():
            temp[i] = '*'

    return ''.join(temp)

print(digit('a1b2cde3~g45hi6'))

2020/12/09 08:37

DSHIN

package main;


import java.util.Arrays;
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        //문자열로 문자를 입력하고 
        //배열로 하나씩 저장하고 배열은 홀수 번째에 있는 값을 *로 변환 하고 
        //배열을 출력
        String str = "";
        str = sc.next();
        char[] arStr = new char[str.length()];
        for (int i = 0; i < arStr.length; i++) {
            if(i%2==1) {
                arStr[i] = '*';             
            }else {
                arStr[i] = str.charAt(i);
            }
        }
        for (int i = 0; i < arStr.length; i++) {
            System.out.print(arStr[i]);
        }
    }
}

2020/12/13 23:51

김준혁

def Every_Other_Digit(strings):

  numbers=['1','2','3','4','5','6','7','8','9','0']

  for_answer=[]

  for i in range(0,len(strings),1):

    if (i+1)%2==0 and strings[i] in numbers:

      for_answer.append("*")

    else:

      for_answer.append(strings[i])

  print("".join(for_answer))


Every_Other_Digit("a1v2cde3~g45hi6")

2020/12/15 16:56

전준혁

text = list('a1b2cde3~g45hi6')
''.join(['*' if text[x].isdigit() and x%2==1 else text[x] for x in range(len(text))])

2021/01/03 15:04

hankyu

s = list(input("Example: "))
for i,c in enumerate(s):
    if((i+1) % 2 == 0):
        if(47<ord(c)<58):
            s[i] = '*'
print("".join(s))        


2021/01/07 18:10

guma go

EOD = 'a1b2cde3~g45hi6'
l = list(EOD)
for index in range(1, len(EOD),2):
    if EOD[index].isdigit():
        l[index]='*'
print(''.join(l))

2021/01/15 15:27

손우민

import java.util.Scanner;

public class EveryOtherDigit {
    public static void main(String[] args) {
        Scanner s = new Scanner(System.in);
        String example = s.nextLine();
        StringBuilder sb = new StringBuilder(example);
        for (int i = 0; i < sb.length(); i++) {
            if ((i + 1) % 2 == 0 && Character.isDigit(sb.charAt(i))) {
                sb.setCharAt(i, '*');
            }
        }
        System.out.println(sb);
    }
}

2021/01/19 00:57

GyuHo Han

line = 'a1b2cde3~g45hi6'
line_list = list(line)
for i, v in enumerate(line_list):
    if i % 2 != 0 and v.isdecimal() == True:
        line_list[i] = '*'

print(''.join(line_list))


2021/02/03 16:40

Ha

a = input("data")
for i in range(len(a)):
    if i%2==1 and a[i].isdigit():
        print("*",end="")
    else:
        print(a[i],end= "")

2021/02/04 21:49

fox.j

    const ary=prompt('문자열을 입력','').split('');
    const number=/[0-9]/;
    const result=ary.map((el,index)=>{
        (index%2==1 && number.test(el))?el='*':el=el;
        return el;
    })

    console.log(result.join(''))

2021/02/08 16:02

wldus

파이썬입니다


str1=input()
str2=str1[0]


for i in range(1,len(str1)):
  if i%2!=0:
    if 48<=ord(str1[i])<=57:    #  if str1[i].isdigit():
      str2=str2+"*"
    else:
      str2=str2+str1[i]
  else:
    str2=str2+str1[i]

print(str)

2021/02/16 23:17

장래희망파이썬마스터

code = "a1b2cde3~g45hi6"
replaced_code = ""


for n in range(len(code)):
    if n%2 == 0:
        replaced_code += code[n]
    elif n%2 == 1:
        if code[n].isdigit() == True:
            replaced_code += "*"
        else :
            replaced_code += code[n]

print(replaced_code)

2021/02/19 10:33

sdfsdf

def convert(s):
    output = ''
    for i in range(0, len(s)):
        if i % 2 != 0 and s[i].isdigit() is True:
            output += "*"
        else:
            output += s[i]
    return output

print(convert('a1b2cde3~g45hi6'))

2021/02/25 03:03

asdfa

def makeAns(str_):
    str2_=""
    for i in range(0, len(str_)):
        if i % 2 == 1 and str_[i].isdigit():
            str2_ = str2_ + "*"
        else:
            str2_ = str2_ + str_[i]
    print(str2_)

makeAns("a1b2cde3~g45hi6")

결과 
a*b*cde*~g4*hi6

2021/04/22 15:24

와장창

def findEvenNum(a):
    temp=[]
    for i in range(len(list(a))):
        if i%2 !=0 and a[i].isnumeric():
            temp.append("*")
        else:
            temp.append(a[i])
    return "".join(temp)

2021/05/01 10:29

최태호

g = [1,2,3,4,5,6,7,8,9,0]
h = "a1b2cde3~g45hi6"
def share(n):
    e = []
    for a in n:
        e.append(a)
    return e
def in(z):
    for b in z:
        if z.index(b)/2 in g and b in g:
            z[z.index] = "*"
    return z
def hab(e):
    t = ""
    for mk in e:
        t = str(t) + str(mk)
    return t
r = share(h)
r = in(r)
print(had(r))


2021/05/20 10:57

고태욱

e = 'a1b2cde3~g45hi6'
q = []
for i in e :
    if 47<ord(i)<58 : q.append('*')
    else : q.append(i)
E = ''.join(q)
print(E)

2021/05/26 11:47

약사의혼자말

#codingdojing_everyOtherDgit

a = 'a1b2cde3~g45hi6'       #immutable
_a = list(a)                #mutable

for i in range(1,len(a),2):
    if _a[i].isdigit(): _a[i] = '*'

print(''.join(_a))

2021/07/28 11:37

Jaeman Lee

파이썬 3.8.10으로 작성했습니다.

sample = 'a1b2cde3~g45hi6'


def star_likes_two(st):
    new_st = ''
    index = 0
    for s in st:
        index += 1
        if index % 2 == 0 and s.isdigit():
            new_st += '*'
        else:
            new_st += s

    return new_st


print(star_likes_two(sample))

2021/08/11 12:03

baek choi

n = input("")
s = ""
nlist = [x for x in n ]
for i in nlist :
    if nlist.index(i) % 2 != 0 and i.isdigit() == True: s += "*"
    else : s += i
print(s)

2021/08/24 13:46

//python

data = 'a1b2cde3~g4hi6'
sun =0
for i in data:
    sun += 1
    if sun % 2 == 0 and i in "0123456789":
        data=data.replace(i,'*')

print(data)

2021/08/27 14:27

한고선

Every Other Digit

S = input("문자열을 입력하세요 : ") n = len(S) S = list(S)

for i in range(n): if i % 2 == 1 and ord(S[i]) >= 48: if ord(S[i]) <= 57: S[i] = "*" S = ''.join(S) print(S)

2021/08/28 13:38

김동현

lst=list(input())
for i in range(len(lst)):
    if i%2 ==1 and lst[i].isdigit():
        lst[i]='*'
print(''.join(lst))

2021/09/22 15:34

ninanino

def change_even_digit(s): 
    for i in range(len(s)):
        if i%2 == 1 and s[i].isdigit():
            print('*',end='')
        else:
            print(s[i],end='')
    print("")

if __name__ == '__main__':
    s = 'a1b2cde3~g45hi6'       
    change_even_digit(s) 

2021/09/28 18:04

서현준

public class Every_Other_Digit {

public static void main(String[] args) {
System.out.print("문자를 입력하세요: ");
Scanner sc = new Scanner(System.in);
String st = sc.nextLine();

for(int i =0 ; i<st.length(); i++) {

    if((i+1)%2==0 &&
            st.charAt(i)<'9' && st.charAt(i)>'0'){
        System.out.print('*');
    }
    else {
        System.out.print(st.charAt(i));
    }
}
}

}

2021/10/28 19:28

초보자

자바스크립트로 풀었습니다.

function tranceform(str) {
  for(var i in str)
    if(i%2 != 0 && isNaN(Number(str[i])) != true) str = str.replace(str[i], '*')      

  return str
}

tranceform("a1b2cde3~g45hi6")

2021/11/26 10:42

유정효

string = input(":")
count = 1
af_string =[]
for i in string:
    if count % 2 == 0:
        if i.isdigit():
            i = "*"
        af_string.append(i)    
    else:
        af_string.append(i)
    count += 1

print("".join(af_string))

2021/12/16 15:39

Jun

sentence = list(input("아무 문장을 입력하세요"))

for i in range(1,len(sentence),2) :
    if ord(sentence[i]) >=48 and ord(sentence[i]) <= 57 :
        sentence.pop(i)
        sentence.insert(i,"*")
a = "".join(sentence)
print(a)

2021/12/22 12:57

양캠부부

str = "a3b1cde6~g45hi6"

s = list(str)

for i in range(len(s)):
    if (i%2==1) and (s[i].isdigit()):
        s[i]="*"

s = "".join(s)

if s=="a*b*cde*~g4*hi6":
    print("정답입니다.")

2022/01/08 01:03

BANG

_input = input("Example : ")

print( "".join( list( map( lambda x : x[1] if x[0]%2 == 0 or x[1] not in "0123456789" else "*",enumerate(_input) ) ) ) )

2022/01/08 16:17

강태호

a = 'a1b2cde3~g45hi6'
b = [x for x in a]

for i in range(1, len(a),2):
    if ord('0')<= ord(a[i]) <= ord('9'):
        b[i] = '*'

print(''.join(b))

2022/02/08 15:49

로만가

def evennum_change(data):
    data = list(data)

    for i, word in enumerate(data):
        if i % 2 != 0 and word.isdigit():
            data[i] = "*"
    return "".join(data)

a = "a1b2cde3~g45hi612"

print(evennum_change(a))

2022/02/21 16:12

김정원

str='a1b2cde3~g45hi6'
str2=list(str)
for x in range(1,len(str),2):
    if 48<=ord(str[x])<=57:
        str2[x]='*'
print(''.join(str2))

2022/03/06 20:49

코딩초보박영규

ord 함수 배우고 갑니다! 48 57이 왜나오나 했네요ㅋㅋ - kh ahn, 2022/03/25 07:55
quiz = "a1b2cde3~g45hi6"

# 문자열 순서 변수 생성
count = 1

# 짝수번째이면서 숫자면 *, 아니면 문자열 출력
for i in quiz:
    if count % 2 == 0 and i.isdigit():
        print("*", end="")
    else:
        print(i, end="")
    count += 1
# 답 =  a*b*cde*~g4*hi6

2022/03/25 07:41

kh ahn

하나의 자리수에 들어올 수 있는 짝수는 2,4,6,8 뿐이라서 요렇게 얌체같이 짜봣슴돠...

public class EvenNum {

    public static void main(String[] args) {

        String str = "a1b2cde3~g45hi6";
        char[] ch = str.toCharArray();
        for (int i = 0; i < ch.length; i++) {
            if (ch[i] == '2' || ch[i] == '4' || ch[i] == '6' || ch[i] == '8') {
                ch[i] = '*';
            }
        }
        String result = new String(ch);
        System.out.println(result);
    }
}

2022/04/08 10:13

휴일의잠만보

a='a1b2cde3~g45hi6'
for i in a:
    if a.index(i)%2==1:
        if 48<=ord(i) and ord(i)<=57:
            i='*'
    print(i,end="")

2022/04/22 20:48

yunjae

import re

def EveryOtherDigit():
    string = input()
    for i in range(len(string)):
        if i % 2 == 1:
            if re.search('\d', string[i]):
                string = string.replace(string[i], '*')

    return print(string)

EveryOtherDigit()        # a1b2cde3~g45hi6

2022/05/04 00:49

Charles

example = 'a1b2cde3~g45hi6'
count = 0
result = ''
for i in example:
    count += 1
    if count % 2 == 0:
        if i in '0123456789':
            result += '*'
        else: result += i
    else: result += i

print(result)

2022/06/18 16:37

김시영

cmd = input("변환할 문장을 입력하시오 :")

cmd_list = []
num = 0

for i in range(0, len(cmd)):                #입력받은 문장을 리스트로 변환
    cmd_list.append(cmd[i])

for n in range(0, len(cmd_list)):           #짝수번째에 있는 글자를 *로 치환
    if n % 2 == 1:
        num = n

        cmd_list[num] = '*'

cmd_char = ''.join(l for l in cmd_list)     #리스트를 문자열로 변환

print(cmd_char)

2022/08/22 20:01

박종훈

파이썬 3.11버전입니다.
문자열 변경에서 a.replace 하면 a의 문자열이 바뀌는 줄 알았는데 a = a.replace 해야하네요
a = input()

for i in range(0,len(a)):
    b = a[i].isdigit()
    if i % 2 == 1 :
        if a[i].isdigit() == True:
            a = a.replace(a[i],"*")
print(a)

2022/11/02 12:35

이웅기

a = list(input())

for i in range(len(a)):
    if i %2 ==1 and a[i].isdecimal():
        a[i] = '*'

print("".join(a))

2022/12/14 21:08

박대선

Python.

origin_sentence = 'a1b2cde3~g45hi6'
def digit_to_star(sentence):
    edited_sentence = '' #결괏값을 넣어 줄 문자열 변수 생성
    for i in sentence:
        if i in "1234567890": #문자열 내의 문자 i가 숫자일 경우
            if (sentence.index(i)+1) % 2 == 0: #index에 1을 더한 수(index는 0부터 시작하므로)가 짝수일 경우(즉, 해당 문자가 짝수 번째 숫자일 경우)
                i = '*' #해당 문자를 *로 치환
                edited_sentence += i #결괏값을 넣을 문자열에 추가
            elif (sentence.index(i)+1) % 2 == 1: #해당 문자가 홀수 번째 숫자일 경우
                edited_sentence += i #결괏값을 넣을 문자열에 그대로 추가
        else: #문자열 내의 문자 i가 숫자가 아닐 경우
            edited_sentence += i #그대로 결괏값에 추가
    return edited_sentence #최종 결괏값 출력
print(digit_to_star(origin_sentence))

2022/12/17 13:51

Frye 'de Bacon

a = input("input your sentence: ")
b = len(a)
result = list(a)

for i in range(b-1):
    if i%2 == 0:    
        for x in a[i+1]:
            if x.isdigit() == True:
                result[i+1] = '*'

result_str = ''.join(result)
print(result_str)

2023/02/18 18:42

제작자

value=list(input())
result=""
for i in range(len(value)):
    if i%2==1 and value[i].isdigit():
        result+="*"
    else:
        result+=value[i]
print(result)

2023/03/12 15:28

Sol Song

x = "a1b2cde3~g45hi6" # 예시
x = list(x) # 리스트 변환

for i in range(1, len(x), 2): # 짝수번째만 받아오도록 순환
    if x[i].isdigit(): # 숫자인지 확인하는 함수
        x[i] = "*" # True일 경우 *로 치환

print(''.join(x)) #문자열로 재변환해서 출력

2023/03/26 17:27

관산정

def eod():
    s = "a1b2cde3~g45hi6"

    for e in s[1::2]:
        if e.isnumeric() == True:
            s = s.replace(e, '*')

    print(s)

eod()

2023/04/20 13:59

장지훈

A = input()

for i in range(1, len(A), 2):
    if A[i].isdigit():
        A = A[:i] + '*' + A[(i+1):]

print(A)

2023/12/04 17:13

윤영식

JAVA입니다.

package question4.every_other_digit;

public class Main {

    public static void main(String[] args) {
        String input = "a1b2cde3~g45hi6";
        char[] inputChars = input.toCharArray();
        String output = "";

        for (int i = 0; i < inputChars.length; i++) {
            String c = Character.toString(inputChars[i]);
            if(i%2 == 1) {
                try {
                    Integer.parseInt(c);
                    c = "*";
                } catch (Exception e) {

                }
            }

            output = output + c;
        }

        System.out.println(output);
    }

}

2025/02/22 22:17

박준우

목록으로