Mario Agolli
Mario Agolli

Reputation: 59

How to combine a String with a List in Python?

I am new to Python and i want to know how to combine a String with all the elements of a List and then save Output in a .txt File. But the window just open and close immediately because the code is wrong. This is my code:

List = [1, 2, 3, 4, 5]

String = input("Please enter a name: ")
Output = String + List
print(Output)

f= open("Text.txt","w+")
f.write(Output + "\n")
f.close()

I am expecting to see this results:

Please enter a name: Username
Username1 Username2 Username3 Username4 Username5

And in the Text File like this:

Username1
Username2
Username3
Username4
Username5

How am i supposed to do this? If the question is not clear please let me know. My first language is not English so is hard for me to explain. Thanks for your time :)

Upvotes: 1

Views: 113

Answers (2)

Ben10
Ben10

Reputation: 498

Following Jacob G. entry your code should look like this:

List = [1, 2, 3, 4, 5]
# input() only works for Python 3.x . Use raw_input() if using python 2.x
InputName = input("Please enter a name: ")
Usernames = [InputName + str(entry) for entry in List]
print(Usernames)

file= open("Text.txt","w+")
for username in Usernames:
   file.write(username)
file.close()

Upvotes: 1

Jacob G.
Jacob G.

Reputation: 29680

I reckon you can use a list comprehension:

List = [1, 2, 3, 4, 5]

String = input("Please enter a name: ")

Output = [String + str(x) for x in List]

print(Output)

Output:

['Username1', 'Username2', 'Username3', 'Username4', 'Username5']

Upvotes: 4

Related Questions