Home > Enterprise >  How to stop a string from separating when adding it to a list?
How to stop a string from separating when adding it to a list?

Time:09-18

Whenever I put a string, it's supposed to take the capital letters' index and put it into a list, but when the string is 10 characters or longer and it has a capital letter after the ninth index, it separates the number when it gets added to the 'capitals' list. How do I make it so it doesn't separate?

string = input()

capitals = []

for current in range(0, len(string)):
    if string[current].isupper():
        capitals  = str(current)

print([int(x) for x in capitals])

CodePudding user response:

short research would help you. here is your answer: Python append() vs. operator on lists, why do these give different results?

TL;DR: using operator adds elements of an array separately, .append adds array itself

CodePudding user response:

You can simply add the integers directly without calling str:

string = 'hello darkness my Old Friend'
capitals = []

for current in range(0, len(string)):
    if string[current].isupper():
        capitals  = [current]  # concatenate the lists

print(capitals)  # [18, 22]

A better code:

string = 'hello darkness my Old Friend'
capitals = []

for i, char in enumerate(string):
    if char.isupper():
        capitals.append(i)  # add index at the end

print(capitals)  # [18, 22]

CodePudding user response:

string = input()

capitals = []

for i, char in enumerate(string):
     if char.isupper():
            capitals.append(i)

    print([int(x) for x in capitals])

CodePudding user response:

I believe the short answer to getting your desired results would be to utilize the "append" function in lieu of performing a " =". Following is a snippet of code.

string = input()

capitals = []

for current in range(0, len(string)):
    if string[current].isupper():
        capitals.append(str(current))   # Used append

print([int(x) for x in capitals])

Following was a sample test.

@Una:~/Python_Programs/Capitals$ python3 Capital.py 
PeterPiperPickedaPeckofPickledPeppers
[0, 5, 10, 17, 23, 30]

Give that a try.

CodePudding user response:

When you add the string variable to the list, Python first transform your string to the another list, which means it iterates the string over the letters. The most Pythonic way to do what you want is iterate over the string using list comprehension.

string = input()

capitals = [i for i, letter in enumerate(string) if letter.isupper()]
print(capitals)

CodePudding user response:

It's because your use of . Use append instead:

while True:
    lst = []
    string = input()
    index = 0

    for i in string: 
        if i.isupper():
            lst.append(index)
        index  = 1

    print(lst)
  • Related