[英]How to print the even-indexed and odd-indexed characters of strings?
Task at hand:手头的任务:
Given a string, S, of length N that is indexed from 0 to N-1, print its even-indexed and odd-indexed characters as 2 space-separated strings on a single line.给定一个长度为 N 的字符串 S,索引从 0 到 N-1,将其偶数索引和奇数索引字符作为 2 个空格分隔的字符串打印在一行上。
The test cases are written such that The first line contains an integer, N (the number of test cases).测试用例的编写使得第一行包含一个整数 N(测试用例的数量)。 Each line i of the N subsequent lines contain a String.后续 N 行中的每一行 i 都包含一个字符串。
Here is my code:这是我的代码:
N = int(raw_input())
for i in range(0,N):
string = raw_input()
evenlist = []
oddlist = []
for item, char in enumerate(strg):
if item % 2 == 0:
evenlist.append(char)
else:
oddlist.append(char)
print ''.join(evenlist), ''.join(oddlist)
Sample run:示例运行:
The first input is:
2
Hacker
Rank
Expected output is:
Hce akr
Rn ak
But I get:但我得到:
HceRn akrak
Here is a link to the assignment that might explain the question better.这是对一个链接分配,可能更好地解释这个问题。
Simpler way to achieve this is via using string slicing :实现这一点的更简单方法是使用字符串切片:
>>> my_str = 'Hacker'
>>> '{} {}'.format(my_str[::2], my_str[1::2])
'Hce akr'
Hence, your entire code could be written as:因此,您的整个代码可以写成:
for _ in range(int(raw_input())):
my_str = raw_input()
print '{} {}'.format(my_str[::2], my_str[1::2])
You can do, also, something like this:你也可以这样做:
inp = raw_input("Enter your input: ")
final = "{} {}".format("".join(inp[k] for k in range(len(inp)) if k % 2 == 0), "".join(inp[k] for k in range(len(inp)) if k % 2 != 0))
In Python-3在 Python-3 中
for i in range(int(input())):
STDIN = input()
print(f"{STDIN[::2]} {STDIN[1::2]}")
input:输入:
2
Hacker
Rank
Output:输出:
Hce akr Rn ak Hce akr Rn ak
Try the below code:试试下面的代码:
N = int(input())
evenlist = [] oddlist = []
for i in range(0,N):
string=input()
evenlist.clear()
oddlist.clear()
for item, char in enumerate(string):
if item % 2 == 0:
evenlist.append(char)
else: oddlist.append(char)
print(''.join(evenlist),''.join(oddlist))
print('')
The solution to the Hacker Rank problem is using string slicing and list. Hacker Rank 问题的解决方案是使用字符串切片和列表。
n= int(input())
r = []
if(n>=1 and n<= 10):
for i in range(n):
r.append(input())
for s in r:
print("{} {}".format(s[::2],s[1::2]))
num = int(input())
mylist = []
for words in range (num):
words = input()
mylist.append(words)
#print(mylist)
i=0
#Considering 0th position as even place here.
while i<len(mylist):
print("Letters at even places = {} Letters at odd places ={}".
format(mylist[i][0:len(mylist[i]):2], mylist[i][1:len(mylist[i]):2]))
i+=1
This is a python solution for your question.这是针对您的问题的python解决方案。
t=int(input("enter number "))
for i in range(1,t+1) :
s=input("String")
even=[]
odd=[]
for j,char in enumerate(s) :
if j%2==0:
even.append(char)
else:
odd.append(char)
print(''.join(even), ''.join(odd))
t = int(input())
for i in range(t):
s = input()
idx = 0
newstr = ''
newstr2 = ''
for letter in s:
if idx % 2 == 0:
newstr = newstr + s[idx]
else:
newstr2 = newstr2 + s[idx]
idx += 1
print(newstr, newstr2)
i=0
for t in range(int(input())):
S = input()
y = len(S)
print(S[i:y+1:2],S[i+1:y+1:2] )
#output= "satisfies all the test cases of HackerRank...."
#using for loop and conditional statement #使用for循环和条件语句
text=input()
for items in range(len(text)):
if items%2==0:
print(text[items],end='')
print(end=' ')
for items in range(len(text)):
if items%2!=0:
print(text[items],end='')
N = int(input())
for _ in range(0,N):
my_str = input()
print ('{} {}'.format(my_str[::2], my_str[1::2]))
#use this , this will perfectly work for this #use this ,这将完全适用于此
I'm a new bee in coding but this is working well with all test cases solved.我是一个新的编码蜜蜂,但这在解决所有测试用例的情况下运行良好。
T=int(input())
for i in range(T):
S=input("")
for item in range(length(S)):
if item%2==0:
print(S[item],end="")
print(end=" ")
for item in range(length(S)):
if item%2!=0:
print(S[item],end="")
print(end='\n')
This also can do by just concatenating the words这也可以通过连接单词来完成
Num_set = int(input())
for item in range(Num_set):
word = input()
new = ""
second = ""
for i in range(len(word)):
if i%2 == 0:
new = new + word[i]
else:
second = second +word[i]
print(new +" "+second)
import java.io.*;
import java.util.*;
public class Solution {
private static void f(String s) {
// TODO Auto-generated method stub
char c[]=s.toCharArray();
int i,j;
for (i = 0; i <c.length;i++)
{
System.out.print(c[i]);
i+=1;
// System.out.print(" ");
}
System.out.print(" ");
for (j = 1; j<c.length;j++)
{
System.out.print(c[j]);
j+=1;
}
}
public static void main(String[] args)
{
// TODO Auto-generated method stub
Scanner sc=new Scanner(System.in);
int s=sc.nextInt();
String s1=sc.next();
f(s1);
String s2=sc.next();
System.out.println();
f(s2);
}
}
Try the below algorithm. It is in Java. However the basic procedure is to
scan the input word string along its length in increments of 2. The even
index characters are printed first using a for loop starting with i = 0 and
by adding an additional i++ inside the loop. The odd
characters are printed starting the for loop from 1 and incrementing by steps
of 2.
import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
import java.util.Arrays;
public class Solution {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt();
for(int iter= 1;iter<=n;iter++)
{
scanner.skip("(\r\n|[\n\r\u2028\u2029\u0085])?");
String myString = scanner.nextLine();
char[] myCharArray = myString.toCharArray();
int t = myString.length();
for(int i = 0; i < t; i++)
{
// Print each sequential character on the same line
System.out.print(myCharArray[i]);
i++;
}
System.out.print(" ");
for(int k = 1; k < t; k++)
{
// Print each sequential character on the same line
System.out.print(myCharArray[k]);
k++;
}
System.out.print("\n");
}
}
}
import java.io.*;
import java.util.*;
public class Solution {
public static void main(String[] args) {
/* Enter your code here. Read input from STDIN. Print output to STDOUT. Your class should be named Solution. */
Scanner s=new Scanner(System.in);
String str;
int T=s.nextInt();
for(int i=0;i<T;i++){
str=s.next();
char c[]=str.toCharArray();
int j,k;
for(j=0;j<c.length;j++){
System.out.print(c[j]);
j+=1;
}
System.out.print(" ");
for(k=1;k<c.length;k++){
System.out.print(c[k]);
k+=1;
}
System.out.println();
}
s.close();
}
}
//In java just to update the above answer for multiple strings they have not added for // loop //在java中只是为了更新他们没有添加的多个字符串的上述答案 //循环
import java.io.*;
import java.util.*;
public class dummy {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
System.out.print("Enter the number of test cases :");
int s=sc.nextInt();
//for loop for multiple strings as per the input
for(int m=1;m<= s;m++)
{
System.out.print("\n Enter the string : ");
String s1=sc.next();
f(s1);
System.out.print();
}
}
private static void f(String s1){
char c[]=s1.toCharArray();
int i,j;
for (i = 0; i <c.length;i++)
{
System.out.print(c[i]);
i+=1;
}
System.out.print(" ");
for (j = 1; j<c.length;j++)
{
System.out.print(c[j]);
j+=1;
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.