Python:从字符串打印特定字符

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/35116496/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 16:00:25  来源:igfitidea点击:

Python: print specific character from string

pythonstringprinting

提问by EVARATE

How do I print a specific character from a string in Python? I am still learning and now trying to make a hangman like program. The idea is that the user enters one character, and if it is in the word, the word will be printed with all the undiscovered letters as "-".

如何从 Python 中的字符串打印特定字符?我仍在学习,现在正在尝试制作一个类似刽子手的程序。这个想法是用户输入一个字符,如果它在单词中,则该单词将与所有未发现的字母一起打印为“-”。

I am not asking for a way to make my idea/code of the whole project better, just a way to, as i said, print that one specific character of the string.

我不是在寻求一种方法来使我的整个项目的想法/代码更好,只是一种方法,正如我所说,打印字符串的一个特定字符。

回答by J. Titus

print(yourstring[characterposition])

Example

例子

print("foobar"[3]) 

prints the letter b

打印这封信 b

EDIT:

编辑:

mystring = "hello world"
lookingfor = "l"
for c in range(0, len(mystring)):
    if mystring[c] == lookingfor:
        print(str(c) + " " + mystring[c]);

Outputs:

输出:

2 l
3 l
9 l

And more along the lines of hangman:

还有更多类似刽子手的内容:

mystring = "hello world"
lookingfor = "l"
for c in range(0, len(mystring)):
    if mystring[c] == lookingfor:
        print(mystring[c], end="")
    elif mystring[c] == " ":
        print(" ", end="")
    else:
        print("-", end="")

produces

产生

--ll- ---l-

回答by Grant Wodny

all you need to do is add brackets with the char number to the end of the name of the string you want to print, i.e.

您需要做的就是在要打印的字符串名称的末尾添加带有字符号的括号,即

text="hello"
print(text[0])
print(text[2])
print(text[1])

returns:

返回:

h
l
e