• Skip to primary navigation
  • Skip to main content
  • Skip to primary sidebar
PythonForBeginners.com

PythonForBeginners.com

Learn By Example

  • Home
  • Learn Python
    • Python Tutorial
  • Categories
    • Basics
    • Lists
    • Dictionary
    • Code Snippets
    • Comments
    • Modules
    • API
    • Beautiful Soup
    • Cheatsheet
    • Games
    • Loops
  • Python Courses
    • Python 3 For Beginners
You are here: Home / Basics / Convert String to Set in Python

Convert String to Set in Python

Author: Aditya Raj
Last Updated: June 29, 2022

Strings are used to manipulate textual data in python. Sometimes, we might need to find the total number of different characters in a text. In such situations, we can convert a string into a set. In this article, we will discuss different ways to convert a string to a set in python. 

Table of Contents
  1. Convert String to Set in Python Using set() Function
  2. Convert String to Set in Python Using Set Comprehension
  3. String to Set in Python Using the add() Method
  4. Conclusion

Convert String to Set in Python Using set() Function

The set() function is used to create a set in Python. It takes an iterable object as its input argument and returns a set containing the elements in the iterable object. 

As we know that a string is an iterable object, we can obtain a set from a string in python using the set() function. For this, we will pass the string to the set() function as its input argument. After executing the set() function, we will get the set with all the characters of the input string. You can observe this in the following example.

myStr = "pythonforbeginners"
mySet = set(myStr)
print("The input string is:", myStr)
print("The output set is:", mySet)

Output:

The input string is: pythonforbeginners
The output set is: {'f', 'i', 'g', 'y', 'o', 'r', 't', 'h', 'p', 'n', 'b', 'e', 's'}

In the above example, you can observe that we have passed the string pythonforbeginners as the input to the set() function. After execution, it has returned a set containing the characters in the string.

Convert String to Set in Python Using Set Comprehension

Set comprehension is used to create a new set from an existing iterable object. The syntax of set comprehension is as follows.

newSet= { expression for element in  iterable }

To convert the string to a set using set comprehension in Python, we will use the input string as the iterable and the characters of the string as the element as well as the expression. After execution, the above statement will convert the string to set. You can observe this in the following example.

myStr = "pythonforbeginners"
mySet = {character for character in myStr}
print("The input string is:", myStr)
print("The output set is:", mySet)

Output:

The input string is: pythonforbeginners
The output set is: {'i', 'n', 'o', 's', 't', 'h', 'b', 'g', 'e', 'r', 'p', 'y', 'f'}

In the above example, we have used set comprehension to convert pythonforbeginners to a set in Python.

String to Set in Python Using the add() Method

The add() method is used to add an element to a set. When invoked on a set, the add() method takes an element as its input argument. After execution, it adds the element to the set if it doesn’t already exist in the set. If the element already exists in the set, nothing happens.

To convert a string to a set using the add() method in python, we will use the following steps.

  • First, we will create an empty set named mySet. For this, we will use the set() function. The set() function, when executed without any argument, returns an empty set.
  • After creating an empty set, we will iterate through characters of the input string using a for loop.
  • During iteration, we will invoke the add() method on mySet and add each character to mySet.
  • After executing the for loop, we will get the output set in the variable mySet. You can observe this in the following example.
myStr = "pythonforbeginners"
mySet = set()
for character in myStr:
    mySet.add(character)
print("The input string is:", myStr)
print("The output set is:", mySet)

Output:

The input string is: pythonforbeginners
The output set is: {'h', 'n', 'g', 'f', 'i', 'b', 'o', 'p', 't', 'e', 's', 'r', 'y'}

In this example, we have used the add() method to convert the string pythonforbeginners to a set.

Conclusion

In this article, we have discussed three ways to convert a string to a set in Python. Out of all the three methods, you can use the approach using the set() function if you need to include all the characters of the string in the set.

If you need to exclude some of the characters of the input string from the set, you can use the approach with the add() method or set comprehension. To know more about python programming, you can read this article on string concatenation in python. You might also like this article on dictionary comprehension in Python.

I hope you enjoyed reading this article. Stay tuned for more informative articles.

Happy Learning!

Related

Recommended Python Training

Course: Python 3 For Beginners

Over 15 hours of video content with guided instruction for beginners. Learn how to create real world applications and master the basics.

Enroll Now

Filed Under: Basics Author: Aditya Raj

More Python Topics

API Argv Basics Beautiful Soup bitly Cheatsheet Code Code Snippets Command Line Comments Concatenation crawler Data Structures Data Types deque Development Dictionary Dictionary Data Structure In Python Error Handling Exceptions Filehandling Files Functions Games GUI Json Lists Loops Mechanzie Modules Modules In Python Mysql OS pip Python Python On The Web Python Strings Queue Requests Scraping Scripts Split Strings System & OS urllib2

Primary Sidebar

Menu

  • Basics
  • Cheatsheet
  • Code Snippets
  • Development
  • Dictionary
  • Error Handling
  • Lists
  • Loops
  • Modules
  • Scripts
  • Strings
  • System & OS
  • Web

Get Our Free Guide To Learning Python

Most Popular Content

  • Reading and Writing Files in Python
  • Python Dictionary – How To Create Dictionaries In Python
  • How to use Split in Python
  • Python String Concatenation and Formatting
  • List Comprehensions in Python
  • How to Use sys.argv in Python?
  • How to use comments in Python
  • Try and Except in Python

Recent Posts

  • Pandas Append Row to DataFrame
  • Convert String to DataFrame in Python
  • Pandas DataFrame to List in Python
  • Solved: Dataframe Constructor Not Properly Called Error in Pandas
  • Overwrite a File in Python

Copyright © 2012–2023 · PythonForBeginners.com

  • Home
  • Contact Us
  • Privacy Policy
  • Write For Us