简体   繁体   English

或者用相应的索引替换字符串中的char

[英]Alternatively replace chars in the string with the corresponding index

How to replace the alternative characters in the string with the corresponding index without iterating? 如何在不进行迭代的情况下用相应的索引替换字符串中的替代字符? For example: 例如:

'abcdefghijklmnopqrstuvwxyz'

should be returned as: 应返回为:

'a1c3e5g7i9k11m13o15q17s19u21w23y25'

I have the below code to achieve this. 我有以下代码来实现这一目标。 But is there a way to skip the loop or, more pythonic way to achieve this : 但是有没有一种方法可以跳过循环,或者通过更多的pythonic方式来实现

string = 'abcdefghijklmnopqrstuvwxyz'
new_string = ''
for i, c in enumerate(string):
    if i % 2:
        new_string += str(i)
    else:
        new_string += c

where new_string hold my required value 其中new_string保留我的必需值

You could use a list comprehension , and re-join the characters with str.join() ; 您可以使用列表 str.join() ,并使用str.join()重新加入字符; the latter avoids repeated (slow) string concatenation): 后者避免了重复的(缓慢的)字符串连接):

newstring = ''.join([str(i) if i % 2 else l for i, l in enumerate(string)])

Note that you can't evade iteration here. 请注意,您不能在此处规避迭代。 Even if you defined a large list of pre-stringified odd numbers here ( odds = [str(i) for i in range(1, 1000, 2)] ) then re-use that to use slice assignment on a list string_list[1::2] = odds[:len(string) // 2] Python has to iterate under the hood to re-assign the indices. 即使您在此处定义了一个很大的预字符串化奇数列表( odds = [str(i) for i in range(1, 1000, 2)] string_list[1::2] = odds[:len(string) // 2] odds = [str(i) for i in range(1, 1000, 2)] ),也可以重用它以在列表string_list[1::2] = odds[:len(string) // 2]上使用切片分配string_list[1::2] = odds[:len(string) // 2] Python必须在后台进行迭代以重新分配索引。 That's the nature of working with an arbitrary-length sequence. 这就是使用任意长度序列的本质。

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

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