简体   繁体   English

Python中的索引字符串

[英]Indexing string in Python

I'm trying to print out only the odd indexed characters of an input string. 我正在尝试只输出输入字符串的奇数索引字符。 I can't use string slicing but instead must use a loop. 我不能使用字符串切片,而是必须使用循环。 How it this done? 怎么做到这一点? Here is my code: 这是我的代码:

string = input("Please enter a string: ")

for each_char in string:
    print("\n%s" % each_char)

You can use the enumerate function 您可以使用enumerate函数

>>> string = input("Please enter a string: ")
Please enter a string: helloworld

>>> for k,v in enumerate(string):
...     if k%2==1:
...         print(v)  # No need \n as print automatically prints newline
... 
e
l
w
r
d

direct string indexing will also work: 直接字符串索引也可以工作:

string = input("Please enter a string: ")

for i in range(1, len(string), 2):
    print(string[i])

output: 输出:

Please enter a string: hello world
e
l

o
l

note the third ( step ) argument of range(start, stop[, step]) . 注意范围的第三个( step )参数range(start, stop[, step])

and - yes - slicing would be much more elegant. - 是的 - 切片会更优雅。


update: because you asked for it - here the version with slicing (you will find more information about slicing in the python tutorial ): 更新:因为你要求它 - 这里有切片的版本(你会在python教程中找到有关切片的更多信息):

for char in string[1::2]:
    print(char)

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

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