8

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 "-".

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.

2

4 Answers 4

9
print(yourstring[characterposition])

Example

print("foobar"[3]) 

prints the letter 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-
Sign up to request clarification or add additional context in comments.

2 Comments

Hey thanks for that, but I know that way to print as in your example the third letter. But I am searching for a way to print a specific letter and its character position. In your case: I search for the "b". The output is the position and the character itself.
Hi. Yeah thats exactly what I need. Thanks buddy.
1

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

Comments

0

Well if you know the character you want to search you can use this approach.

i = character looking for
input1 = string

if i in input1:
    print(i)

you can change the print statement according to your logic.

Comments

0
name = "premier league"
for x in name:
      print(x)

Result shown below:-

enter image description here

To print specific characters of the given string. For example to print 'l' from the given string

name = "premier league"
for x in name:                                                                        
   if x == "l":                                                                      
      print("element found: "+x)

enter image description here

1 Comment

Copy-paste the outputs, please don't post screenShots of your terminal :)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.