Yasaman Shokri
Yasaman Shokri

Reputation: 155

How to convert an user input to a set in python?

I want to make a set from alphabets of a user input for example: input is: "something" and the output must be: { 's', 'o', 'm', 'e', 't', 'h', 'i', 'n', 'g'} I wrote it like below but it caused an error saying the input must be iterable!

 str = print("please enter a string:")
 str_set = set(str)
 print(str_set)

Upvotes: 0

Views: 15958

Answers (5)

John Patrick Kokar
John Patrick Kokar

Reputation: 67

First you need to use input instead of print. print is to print something on terminale/ command line, it is also possible to get user input with your script without (str =) like so :

import sys

def printerd():
    print('please enter a string:', end='')
    sys.stdout.flush()
    data = sys.stdin.readline()[:-1]
    print(list(data))

 printerd()

this will print please enter a string : and wait for user to type something and then print an array ['s', 'o', etc].

Upvotes: 0

samuel
samuel

Reputation: 13

There are some rules for naming variables, one of which is that you can't use reserved words such as: print, str, int, float, input, etc. for naming your variables. You can learn more about the rules here: https://www.geeksforgeeks.org/python-variables/

And about the code, I believe this would help:

    user_input = input("Please enter a string: ")
    list_of_letters = list(user_input)
    print(list_of_letters)

Upvotes: 0

Tomasz Lipiński
Tomasz Lipiński

Reputation: 85

  1. First of all you shouldn't named variables using buildins objects names like: str, int, float and so one.

  2. print function will return None and isn't iterable, so you get an error. You should use input function instead.

user_input = input("please enter a string:")

Upvotes: 0

BLimitless
BLimitless

Reputation: 2605

You have two errors:

  1. str is built-in, so you need a different name.
  2. You need input to catch the input, not just print.
str1 = input("please enter a string:")
str_set = set(str1)
print(str_set)

You could also shorten to just one line if you want to be more concise, but when trading concision against readability, lean towards readability:

str_set = set(input("please enter a string: "))

Upvotes: 1

quamrana
quamrana

Reputation: 39404

If you want to input something from the user you should use the input() function:

s = input("please enter a string:")
str_set = set(s)
print(str_set)

Upvotes: 2

Related Questions