简体   繁体   English

如何从 Python 中的给定字符串打印偶数和奇数字符

[英]How to print even and odd chars from a given string in Python

I was doing a problem in Python: Problem statement我在 Python 中遇到问题:问题陈述

However, my code is not getting the output I want.但是,我的代码没有得到我想要的 output。 I want to store the strings in an array (2xtestcases) (given by the size of 'testcases' and then for each word loop over the index of the strings of the arrays and print the even and uneven word.我想将字符串存储在一个数组(2xtestcases)中(由'testcases'的大小给出,然后为每个单词循环遍历 arrays 的字符串索引并打印偶数和不均匀单词。

import numpy as np
import array as arr

# testcases
testcases = int(input())
# list of empty strings
strings = [None] * testcases

# list of translated strings
strings_translated = np.zeros((2, testcases))

for i in range(0, testcases):
    strings[i] = input()
    for k in strings[i]:
        if k % 2 == 0:
            strings_translated[1, i] = strings_translated[1, i] + k
        else:
            strings_translated[2, i] = strings_translated[2, i] + k

for i in range(0, testcases):
    print(strings_translated[1, i] + strings_translated[2, i])

I get the following error:我收到以下错误:

if k % 2 == 0:
TypeError: not all arguments converted during string formatting

Would you like to try this: (just a sample code to give you hints)你想试试这个吗:(只是一个示例代码给你提示)

N = len(s)   # your string's len

evens = ''.join(s[i] for i in range(0, N,2))  # 'Hce' 

# then do the odds character as well

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何附加偶数和奇数字符python - How to append even and odd chars python 如何在Python中以字符串形式逐步输出字符 - How to incrementally print the chars in a String in Python 如何在 Python 中打印此输出 [自上而下(偶数)] [自下而上(奇数)] - How to to print this output in Python [top down (even)] [bottom up (odd)] Python 问题 从用户获取输入 N 为每个偶数打印 'EVEN' 为每个奇数打印 'ODD',从 1 到 N - Python Problem Take input N from the user Print 'EVEN' for every even number Print 'ODD' for every odd number, from 1 to N 奇数偶数字符串-Python - Odd Even String- Python 在给定条件奇数或偶数的情况下,如何对列表中的偶数或奇数求和? - How to sum even or odd numbers in a list given the condition odd or even? 给定输入时,如何从列表中打印随机字符串? (Python) - How to print a random string from a list, when given an input? (Python) 使用列表推导,我想打印偶数,并且字符串表示“偶数”表示“偶数”,“奇数表示奇数” - Using List Comprehension I want to Print odd even with string indicating “Even” for even numbers and “Odd for odd numbers” 在 python 中打印给定范围内的奇数 - Print odd numbers in a given range in python 使用 python 打印范围之间的奇数或偶数列表。 输出应与字符串在一行中 - Print the list of odd or even numbers between a range using python. Output should be in a single line along with the string
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM