Home > Software design >  How do I output the first character of all strings that are in a list?
How do I output the first character of all strings that are in a list?

Time:02-14

For example if I have the list:

['Bob\n', "Joe\n", "Frank\n", "Bill"]

and want to get the output

B
J
F
B

CodePudding user response:

Use a list comprehension:

inp = ["Bob\n", "Joe\n", "Frank\n", "Bill"]
output = '\n'.join([x[0] for x in inp])
print(output)

This prints:

B
J
F
B

CodePudding user response:

use [] operator to print first character of string

l = ['Bob\n', "Joe\n", "Frank\n", "Bill"]
for s in l:
    print(s[0])

output:

B
J
F
B

CodePudding user response:

tmp = ['Bob\n', "Joe\n", "Frank\n", "Bill"]
print([i[0] for i in tmp])
  • Related