Pulling Characters from a string and making a list

798 views python
-2

Sorry for bothering for an easy question but I wasn't able to come up with a solution. So far I have done the solution below. I am trying to pull out the secondary characters from "koc" and make them a list. The solution below only print out the secondary characters. I want to create a list from those characters. Thank You

koc = "The weather is very nice today I feel warmer!"

sent = koc.title()

for kc in sent.split():

    if len(kc) == 1:
        continue
    else:
        print(kc[1])

answered question

"Sorry" for downvoting, but there are numerous tutorials telling you how to do that.

do you have a link because I couldn't find one. Thank you

3 Answers

3

Use a list comprehension:

print([x[1] for x in  "The weather is very nice today I feel warmer!".split() if len(x)>1])

posted this
5

If I understand issue, you are going convert a string to a list of its chars. here is a sample code you can use:

line = "The weather is very nice today I feel warmer!"
chars = []
chars.extend(line)
print(chars) 

posted this
8

In the spirit of keeping the code as close to your code, here is a simple solution. See the inline comments for more details. BTW - removed the unnecessary else statement to keep things from nesting :)

koc = "The weather is very nice today I feel warmer!"

sent = koc.title()

output_ls = [] # initiate list here
for kc in sent.split():

    if len(kc) == 1:
        continue

    output_ls.append(kc[1]) # add to the end of the list

output_ls:

['h', 'e', 's', 'e', 'i', 'o', 'e', 'a']

posted this

Have an answer?

JD

Please login first before posting an answer.