Zac Cotterell
Zac Cotterell

Reputation: 129

How to convert a user_input into a list?

I need some help this and I'm sure when this is answered it will be pretty simple that I didn't think of. But here it is:

I'm trying to get this code:

forename = [input("Forename: ")]
forenameFirstLetter = forename[0]

email = str(forenameFirstLetter) + "." + surname + "@TreeRoad.net"
print ("This is the students email address:" + email)

to print:

[email protected]

Instead I'm getting this error: TypeError: Can't convert 'list' object to str implicitly

so how would I go about forename into a list so I can print the first letter and then back into a string so i can add it to other string?

Upvotes: 2

Views: 151

Answers (4)

Juan T
Juan T

Reputation: 1219

What you did wrong:

What you where trying to do was creating a list whose only element was a string. When it is a list, forename[0] will take the first (and only) element of that list (Just the string as if it was taken directly from input()), but not from the string.


How to fix it:

It is not necessary to convert it to list, slice notation allows to use:

forename = input("Forename: ")
forenameFirstLetter = forename[0]

So, now it's unnecessary to convert to string later:

email = forenameFirstLetter + "." + surname + "@TreeRoad.net"
print ("This is the students email address:" + email)

To understand better slicing strings:

 0 | 1 | 2 | 3 | (index)
 f | o | o | . | (string)

When you slice a string:

s = "foo."

s[0] #is "f" because it corresponds with the index 0
s[1] #is "o"
s[2] #is "o"
s[0:2] #takes the substring from the index 0 to 2. In this example: "foo"
s[:1] #From the start of the string until reaching the index 1. "fo"
s[2:] #From 2 to the end, "o."
s[::2] #This is the step, here we are taking a substring with even index.
s[1:2:3] #You can put all three together

So the syntax is string[start:end:step].

For use in lists is very similar.

Upvotes: 4

Mateusz Korycinski
Mateusz Korycinski

Reputation: 1057

What you need is:

forename = input('Forename: ')
surname = input('Surname: ')

email = forename[0] + "." + surname + "@TreeRoad.net"
print ("This is the students email address:" + email)

You can also use simpler to read string formatting:

email = '%s.%[email protected]' % (forename[0], surname)

Upvotes: 0

Joseph Chotard
Joseph Chotard

Reputation: 695

That is because you are trying to convert the string to a list you can just slice the string itself.

Change this line:

forename = [input("Forename: ")]

to

forename = input("Forename: ")

By doing this you are getting the first letter of the string. I would recommend reading this article on string slicing to learn more about it.

Upvotes: 2

Akshay Choulwar
Akshay Choulwar

Reputation: 26

Don't take input inside the list take string as input and apply split function on it and it will be converted into list.

Upvotes: -1

Related Questions