Python – Print on screen the letter in position "x"
Question:
I need to find and print a letter of a word.
For example: wOrd
I want to print only the uppercase letter. I tried using "find()" it shows me the position of the letter but I can’t show the letter "O" it shows "1".
Is it possible to do that?
Answers:
s='wOrd'
[x for x in s if x==x.upper()]
['O']
''.join(x for x in s if x==x.upper())
'O'
More general case:
s='My Name is John'
[x for x in s if x==x.upper() and x!=' ']
['M', 'N', 'J']
''.join(x for x in s if x==x.upper() and x!=' ')
'MNJ'
Welcome to StackOVerflow.
1 is the index of the letter "O"
Once you have the index you can simply use it to print or do whatever else.
test = "wOrd"
print(test[1])
Above will print "O"
Using the str.isupper
method:
s = "wOrd"
# print every upper-case character
print(*(char for char in s if char.isupper()))
# print every upper-case character - functional programming
print(''.join(filter(str.isupper, s)))
# print the 1st upper-case character. If none returns None
print(next((char for char in s if char.isupper()), None))
I need to find and print a letter of a word.
For example: wOrd
I want to print only the uppercase letter. I tried using "find()" it shows me the position of the letter but I can’t show the letter "O" it shows "1".
Is it possible to do that?
s='wOrd'
[x for x in s if x==x.upper()]
['O']
''.join(x for x in s if x==x.upper())
'O'
More general case:
s='My Name is John'
[x for x in s if x==x.upper() and x!=' ']
['M', 'N', 'J']
''.join(x for x in s if x==x.upper() and x!=' ')
'MNJ'
Welcome to StackOVerflow.
1 is the index of the letter "O"
Once you have the index you can simply use it to print or do whatever else.
test = "wOrd"
print(test[1])
Above will print "O"
Using the str.isupper
method:
s = "wOrd"
# print every upper-case character
print(*(char for char in s if char.isupper()))
# print every upper-case character - functional programming
print(''.join(filter(str.isupper, s)))
# print the 1st upper-case character. If none returns None
print(next((char for char in s if char.isupper()), None))