I want the output for this code to be a list how should I do it I'm very new to python so sorry if this look silly
s = "Hello, World!"
for i in range(len(s) 1):
a = print(s[:i])
print(a)
The output would be:
H
He
Hel
Hell
Hello
Hello,
Hello,
Hello, W
Hello, Wo
Hello, Wor
Hello, Worl
Hello, World
Hello, World!
How can I output it like:
[ "H",
"He",
"Hel",
"Hell",
"Hello",
"Hello,",
"Hello, ",
"Hello, W",
"Hello, Wo",
"Hello, Wor",
"Hello, Worl",
"Hello, World",
"Hello, World!",
]
CodePudding user response:
This is exactly what the itertools.accumulate
built-in function does:
from itertools import accumulate
result = list(accumulate('Hello, World!'))
If you prefer something maybe easier to understand:
s = 'Hello, World!'
result = []
for i in range(len(s) 1):
result.append(s[:i])
The previous approach can also be written using a list comprehension:
s = 'Hello, World!'
result = [s[:i] for i in range(len(s) 1)]
CodePudding user response:
You can create an empty list (let's call it string_list
)at the beginning of your code and append each substring to that list with string_list.append(s)
instead of printing the substring.
CodePudding user response:
s = "Hello, World!"
my_list = []
for i in range(len(s)):
my_list.append(s[:i 1])
my_list
Output:
['H',
'He',
'Hel',
'Hell',
'Hello',
'Hello,',
'Hello, ',
'Hello, W',
'Hello, Wo',
'Hello, Wor',
'Hello, Worl',
'Hello, World',
'Hello, World!']
The pythonic way is a list comprehension:
s = "Hello, World!"
[s[:i 1] for i in range(len(s))]
CodePudding user response:
Is this what you're looking for :
print("[")
[print('"' s[:i] '"') for i in range(len(s) 1)]
print("]")
CodePudding user response:
s = "Hello, World!"
qqq = []
for i in range(len(s) 1):
a = print(s[:i])
qqq.append(s[:i])
print(a)
print(qqq)