0

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])
MattDMo
  • 100,794
  • 21
  • 241
  • 231
eclipse
  • 1
  • 1

6 Answers6

1

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

kkkkrkrkkk
  • 21
  • 7
0

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]
Valentin Goldité
  • 1,040
  • 4
  • 13
0
string = input()

capitals = []

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

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

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.

NoDakker
  • 3,390
  • 1
  • 10
  • 11
0

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)
Boris Silantev
  • 753
  • 3
  • 13
0

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)