简体   繁体   English

用Python中另一个字符串的第n个字符创建一个字符串

[英]Create a string with every nth character of another string in Python

I would like to split a string with the result being a string consisting only of every nth character of the original string. 我想分割一个字符串,结果是一个仅由原始字符串的第n个字符组成的字符串。 My first approach looks like this (and works): 我的第一种方法看起来像这样(可行):

#Divide the cipher text in the estimated number of columns
for i in range(0,keyLengthEstimator):
    cipherColumns.append(cipherstring[i])

for i in range(keyLengthEstimator,len(cipherstring)):
    if i % keyLengthEstimator == 0:
        cipherColumns[0] += cipherstring[i]
    elif i % keyLengthEstimator == 1:
        cipherColumns[1] += cipherstring[i]
    elif i % keyLengthEstimator == 2:
        cipherColumns[2] += cipherstring[i]
    elif i % keyLengthEstimator == 3:
        cipherColumns[3] += cipherstring[i]
    elif i % keyLengthEstimator == 4:
        cipherColumns[4] += cipherstring[i]

I have the feeling, that there is a more efficient way to do it. 我觉得有一种更有效的方法可以做到这一点。 In Matlab there would be the reshape function, is there a similar function in Python? 在Matlab中会有reshape函数,Python中有类似的函数吗?

Why not simply: 为什么不简单:

#Divide the cipher text in the estimated number of columns
for i in range(0,keyLengthEstimator):
    cipherColumns.append(cipherstring[i])

for i in range(keyLengthEstimator,len(cipherstring)):
    cipherColumns[i % keyLengthEstimator] += cipherstring[i]

You could slice the string N times, specifying a step of N for each one: 您可以将字符串切片N次,为每个字符串指定N的步长:

>>> s = "Hello I am the input string"
>>> columns = 5
>>> seq = [s[i::columns] for i in range(columns)]
>>> print seq
['H  i n', 'eItnsg', 'l hpt', 'laeur', 'om ti']
>>> print "\n".join(seq)
H  i n
eItnsg
l hpt
laeur
om ti

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM