python - 在循环中迭代字符串中的每个第 n 个元素 - python

标签 python string loops iteration

如何迭代字符串中的每隔一个元素?

一种方法是(如果我想迭代每个第 n 个元素):

sample = "This is a string"
n = 3 # I want to iterate over every third element
i = 1
for x in sample:
    if i % n == 0:
        # do something with x
    else:
        # do something else with x
    i += 1

有什么“Pythonic”方法可以做到这一点吗? (我很确定我的方法不好)

最佳答案

您可以使用step例如sample[start:stop:step]

如果你想迭代每个第二个元素,你可以这样做:

sample = "This is a string"

for x in sample[::2]:
    print(x)

输出

T
i

s
a
s
r
n

关于python - 在循环中迭代字符串中的每个第 n 个元素 - python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51121911/

相关文章:

python - 创建一个字典,其值每次使用时都会更新

python - 无法编译微软示例CppAndPython

python - Selenium 中的 IF/THEN 语句

c - [GTK]将 g_signal_connect 中的循环计数器传递给 g_callback

python - str.startswith 是如何真正起作用的?

c++ - 从字符串输入中删除特定单词

c++ - Word 解读程序 - C++

Javascript - PHP 在 JavaScript 上的 Substr() 替代品

php - 使用 PHP 的 foreach 将逻辑仅应用于数组中的某些键

java - "Running total returns false value"