[英]Python: print specific character from string
How do I print a specific character from a string in Python?如何从 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 "-".这个想法是用户输入一个字符,如果它在单词中,该单词将打印所有未发现的字母为“-”。
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.我不是在寻求一种方法来使我的整个项目的想法/代码更好,只是一种方法,正如我所说,打印字符串的一个特定字符。
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-
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, ie您需要做的就是在要打印的字符串名称的末尾添加带有字符编号的括号,即
text="hello"
print(text[0])
print(text[2])
print(text[1])
returns:返回:
h
l
e
Well if you know the character you want to search you can use this approach.好吧,如果您知道要搜索的字符,则可以使用此方法。
i = character looking for i = 正在寻找的字符
input1 = string输入 1 = 字符串
if i in input1:
print(i)
you can change the print statement according to your logic.您可以根据您的逻辑更改打印语句。
What if i want to print "llo" from "hello world!"如果我想从“hello world!”打印“llo”怎么办? using for loop?使用for循环?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.