Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: print specific character from string

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.

like image 256
EVARATE Avatar asked Jan 31 '16 16:01

EVARATE


People also ask

How do I print a specific character in a string in Python?

Use string slicing to print specific characters in a string, e.g. print(my_str[:5]) . The print() function will print the specified character or slice of the string to the terminal.

How do you get a single character from a string in Python?

In python String provides an [] operator to access any character in the string by index position. We need to pass the index position in the square brackets, and it will return the character at that index.

How do I extract a specific part of a string in Python?

Getting a substring of a string is extracting a part of a string from a string object. It is also called a Slicing operation. You can get substring of a string in python using the str[0:n] option.

How do I print a specific word in a string in Python?

Approach: Split the string using split() function. Iterate in the words of a string using for loop. Calculate the length of the word using len() function. If the length is even, then print the word.


2 Answers

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-
like image 103
J. Titus Avatar answered Oct 08 '22 04:10

J. Titus


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
like image 40
Grant Wodny Avatar answered Oct 08 '22 03:10

Grant Wodny