Reputation:
So im trying to get first letters of words(excluding first word, i already solved that) in a sentence.
But it appends spaces to the list.
Would appreciate if you help.
Here's the code:
lst = []
for t in (input()):
if t == " ":
lst.append(t)
print(*lst, sep="")
input1: asd dfd yjs
output1: dy
Upvotes: 0
Views: 145
Reputation: 413
A lot great answers already and this is good case for split. If you specifically need to collect the next token after a special token in a stream of tokens, here are some other options:
inp = "asd dfd yjs"
lst = []
for a, b in zip(inp[:-1],inp[1:]):
if a == " ":
lst.append(b)
print(*lst, sep="")
# With comprehensions - my choice
print("".join([b for a, b in zip(inp[:-1],inp[1:]) if a == " "]))
# With functional approach
from functools import reduce
from operator import add, itemgetter
def has_prior_space(x):
return x[0] == " "
print(reduce(add, map(itemgetter(1), filter(has_prior_space, zip(inp[:-1], inp[1:])))))
In Python 3.10, there will be a new pairwise
iterator that does this type of "2 at a time" iteration specifically: zip(inp[:-1],inp[1:])
Upvotes: 0
Reputation: 964
just this:
''.join([s[0] for s in input().split()[1:]])
step by step:
if input()
returns asd dfd yjs
split string (more):
input().split() # output: ['asd', 'dfd', 'yjs']
sub list (more):
input().split()[1:] # output: ['dfd', 'yjs']
one line loop (more):
[s[0] for s in ['dfd', 'yjs']] # output: ['d', 'y']
sub string (more):
s="dfd"
s[0] # output: d
concat list of strings (more):
''.join(['d', 'y']) # output: dy
Upvotes: 3
Reputation: 54168
You may
x.split()
[1:]
(from index 1 to the end)x = input(">")
result = ""
for word in x.split()[1:]:
result += word[0]
print(result) # dy
Using a generator and str.join
:
x = input(">")
result = ''.join(word[0] for word in x.split()[1:])
Upvotes: 2
Reputation: 4449
You're getting spaces because that's what you asked for. Read your code out loud and it will probably make sense:
if t == " ":
lst.append(t)
If t
is a space, append it to lst
Seems clear that you will only get spaces.
You want the character after t
to be appended. There's two ways to do that using your for
loop method: 1) if t
is a space, append the next character; 2) if the previous character was a space, append t
. Here's how you might implement #2:
lst = []
prev_char = None
for t in (input()):
if prev_char == " ":
lst.append(t)
prev_char = t
print(*lst, sep="")
This will print the first character of ever word except the first word. Initialize last_char
to a space to include the first word.
Upvotes: 2
Reputation: 13641
A simple example:
lst = []
get_next = False
for t in input():
if t == " ":
get_next = True
elif get_next:
lst.append(t)
get_next = False
print(*lst, sep="")
Upvotes: 0