Python import string module named

Import Python Module by String Name

In Python, when building a framework or code generation tool, you might need to programmatically build a string representing the name of a module you want to import. How would you import a module if you have it’s name as a string? Here’s how to do it with importlib! Note that this feature was introduced in Python 3.1 but there is a 2.7 version of importlib though less featured.

Learn more about how Python searches for imports, how the `PYTHONPATH` environment variable is used, and how to use `sys.path` in my Python import, sys.path, and PYTHONPATH Tutorial.

Learn more about Python virtual environments which allow you to create isolated Python environments with different import paths with my Python Virtual Environments Tutorial.

Use importlib to programmatically import modules

The importlib provides a simple import_module function that accepts a string name with dot separators. It works just like a normal import except it uses a string to store the name. On import, the file is executed and the module object is returned. If you only need the code run on import it is not necessary to store the returned module.

import importlib

# Contrived example of generating a module named as a string
full_module_name = "mypackage." + "mymodule"

# The file gets executed upon import, as expected.
mymodule = importlib.import_module(full_module_name)

# Then you can use the module like normal
mymodule.func1()
mymodule.func2()

Conclusion

You should now know how to dynamically import modules using a module name stored in a string.

Источник

Python string Module

In this article, we are going to learn the Python string module. the string is a built-in module in Python which is used to precess the string.
the string is a built-in module, That means the string is pre-installed with Python. In the previous tutorial, we have seen the Python string HTML module.

To understand this example you should have basic knowledge of Python Programming .

  • 1 Python String Module:
  • 2 Python String Module Properties:
    • 2.1 string.ascii_letters
    • 2.2 string.ascii_lowercase:
    • 2.3 string.ascii_uppercase:
    • 2.4 string.digits:
    • 2.5 string.hexdigits:
    • 2.6 string.octdigits:
    • 2.7 string.punctuation:
    • 2.8 string.whitespace:
    • 2.9 string.printable:
    • 3.1 capwords(s, sep = None)
      • 3.1.1 Example 1:
      • 3.1.2 Example 2:
      • 4.1 Formatter:
      • 4.2 Template:

      Python String Module:

      Python provides a built-in module named string which provides lots of functions and properties to precess the string.

      Python string module is a built-in Python module that means you don’t need to install it by using pip. To use the string module in Python you need to import using the import keyword.

      Python String Module Properties:

      Let’s look constants, define in the string module.

      string.ascii_letters

      This constants return the combination of ascii.lowercase and ascii.uppercase letters.

      import string x = string.ascii_letters print(x) 
      abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ

      string.ascii_lowercase:

      string.ascii_lowercase constants return the lowercase letters.

      import string x = string.ascii_lowercase print(x)
      abcdefghijklmnopqrstuvwxyz

      string.ascii_uppercase:

      string.ascii_uppercase constants return the upper case letters.

      import string x = string.ascii_uppercase print(x)
      ABCDEFGHIJKLMNOPQRSTUVWXYZ

      string.digits:

      string.digits return the digits.

      import string x = string.digits print(x)

      string.hexdigits:

      The string.hexdigits return the hexadecimal:

      import string x = string.hexdigits print(x)

      string.octdigits:

      The string.octdigits return the hexadecimal.

      import string x = string.hexdigits print(x)

      Output will be:- 01234567

      string.punctuation:

      The string.punctuation return the punctuations.

      import string x = string.punctuation print(x) 

      string.whitespace:

      The string.whitespace return the whitespaces.

      import string x = string.whitespace print(x)

      string.printable:

      The string.printable constants return the combination of ascii_letters, digits, punctuations and whitespace.

      import string x = string.printable print(x)
      0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!"#$%&'()*+,-./:;?@[\]^_`<|>~ 

      Python string module Helper Functions:

      string module provides function which are used to process the string.

      capwords(s, sep = None)

      The string.capwords() helper function is used to split the string into the words using str.split() function. Then it capitalizes each word using str.capitalize() function. Finally, it joins the capitalized words using str.join().

      Example 1:

      import string txt = "Programming Funda is programming portal" x = string.capwords(txt) print(x)

      Output will be:- Programming Funda Is Programming Portal

      Example 2:

      import string txt = " Programming Funda is programming portal " x = string.capwords(txt, "g") print(x)
      progRamming funda is progRamming portal

      Python string module Classes:

      Python built-in string module provide two class Formatter and Template.

      Formatter:

      Formatter class is used to format the string same as str.format() function.

      from string import Formatter formatter = Formatter() print(formatter.format('', portal = 'ProgrammingFunda is a portal')) print(formatter.format('<> ', 'Programming Funda', portal = 'is a programming portal')) print('<> '.format('Welcome to the', portal = 'programming Funda')) 
      ProgrammingFunda is a portal Programming Funda is a programming portal Welcome to the programming Funda

      Template:

      Template class is used to create the string template for simple string substitute.

      from string import Template temp = Template("$name is the Founder of $portal") s = temp.substitute(name = "Vishvajit Rao", portal = "Programming Funda") print(s)
      Vishvajit Rao is the Founder of Programming Funda

      Conclusion:

      In this tutorial, you have learned about the Python string module. string module in Python provides lots of functions that are used to process the string. This is the legitimate module to work with string.

      I hope this tutorial will help you, if you like this article, please comment and share with your friends who want to learn Python programming from scratch to advanced.

      For More Information:- Click Here

      Источник

      How to Import Python Module from String Name

      In this Python tutorial, we will explore how to import a Python Module using a string representation of its name. We will achieve this task using the Python importlib module, which provides us with the required functionality.

      It is important to note that this library is only available on Python 2.7, and Python 3.1 and above.

      Import Python Module using importlib

      Normally, when we want to import modules/libraries in Python, we follow the below format.

      However, we may wish to import libraries during run-time, or based on user input. This may lead us to trying the following approach(es).

      import "matplotlib" # Wrong str = "matplotlib" import str # Wrong

      Both of the above approaches are wrong, and will not work as intended. This is where the Python importlib library comes in.

      We will be using the importlib library’s import_module() function. This function takes as parameter, a string that represents the library you wish to import.

      Let’s take a look at how to import a module using this function.

      import importlib lib = importlib.import_module("random") for i in range(5): print(lib.randint(1, 10))

      Once you have called import_module() function, it will return a library object. Every time you want to use a function from the imported library, you must do it through the library object.

      In the above example, we imported the random library, used to generate random numbers. It has a variety of different functions, one of which is randint() . Normally we might do random.randint() to call this, but when using importlib, we need to do lib.randint() . ( lib is an arbitrary name)

      More about importlib

      Some special cases can arise, such as when you need to import a sub-module. The below code shows how you would go about doing so.

      import importlib lib = importlib.import_module("matplotlib.pyplot") lib.plot([1, 2, 3, 4], [1, 4, 9, 16]) lib.show()

      Normally, this would have been the following statement.

      For more information about importlib, please refer to the dedicated section for the Python importlib module.

      This marks the end of the “Import Python Module from String” Tutorial. Any suggestions or contributions for CodersLegacy are more than welcome. Questions regarding the tutorial content can be asked in the comments section.

      Источник

      How to import modules from string in Python?

      How to import modules from string in Python?

      Dynamic module importing made easy with Python's importlib

      In Python, you can use the import statement to import a module or package into your code. However, sometimes you may want to dynamically import a module or package from a string, rather than hard coding the module or package name. In this article, we'll explore how to import modules from string in Python using the importlib module.

      The importlib module provides a number of functions for interacting with the import system, including the import_module function, which can be used to import a module from a string. To use the import_module function, you need to pass it the name of the module as a string, and it will return the module object.

      For example, to import the math module from a string, you can use the following code:

      import importlib module_name = 'math' module = importlib.import_module(module_name) 

      Once you have the module object, you can use it like any other module, accessing its attributes and functions using the dot notation. For example, to use the pi constant from the math module, you can use the following code:

      import importlib module_name = 'math' module = importlib.import_module(module_name) print(module.pi) # 3.141592653589793 

      You can also use the import_module function to import submodules or subpackages from a string. To do this, you simply need to include the submodule or subpackage name in the string, separated by a dot. For example, to import the urllib.parse module from a string, you can use the following code:

      import importlib module_name = 'urllib.parse' module = importlib.import_module(module_name) 

      In addition to the import_module function, the importlib module also provides the import_from_string function, which allows you to import a module or object from a string containing the fully qualified name of the module or object. For example, to import the Decimal class from the decimal module from a string, you can use the following code:

      import importlib module_name = 'decimal.Decimal' module = importlib.import_from_string(module_name) decimal = module('3.14') print(decimal) # 3.14 

      In conclusion, the importlib module provides a number of functions for importing modules and objects from string in Python. By using these functions, you can dynamically import modules or objects

      Any thoughts? Write it down in the comments.

      For more such crispy blogs daily, follow Dev.Junction, subscribe to our newsletter and get notified.

      Did you find this article valuable?

      Support Dev.Junction by becoming a sponsor. Any amount is appreciated!

      Источник

      Читайте также:  Слои по горизонтали
Оцените статью