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.
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.
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.
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.
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.
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-
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With