7

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.

EVARATE
  • 115
  • 1
  • 1
  • 9
  • 1
    Possible duplicate of [How to check a string for specific characters?](http://stackoverflow.com/questions/5188792/how-to-check-a-string-for-specific-characters) – oystein-hr Jan 31 '16 at 16:57
  • 1
    Possible duplicate of [Is there a way to substring a string in Python?](http://stackoverflow.com/questions/663171/is-there-a-way-to-substring-a-string-in-python) – MattDMo Jan 31 '16 at 16:59

4 Answers4

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-
J. Titus
  • 9,535
  • 1
  • 32
  • 45
  • 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. – EVARATE Jan 31 '16 at 17:03
  • Hi. Yeah thats exactly what I need. Thanks buddy. – EVARATE Jan 31 '16 at 17:20
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
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.

Dilip Singh
  • 21
  • 1
  • 3
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