如何在python 3中将字符串中的字符列入白名单?

时间:2019-05-15 23:57:57

标签: python python-3.x string strip

我的问题很简单,我正在尝试从字符串中去除任何非A-Z或0-9的字符。

基本上,这是我要尝试的过程:

whitelist=['a',...'z', '0',...'9']

name = '_abcd!?123'

name.strip(whitelist)

print(name)

>>> abcd123

要知道的重要一点是,我不能只在名称中打印有效字符。我需要实际使用处于更改状态的变量。

3 个答案:

答案 0 :(得分:2)

您可以使用re.sub并提供与您要删除的内容完全匹配的模式:

import re
result = re.sub('[^a-zA-Z0-9]', '', '_abcd!?123')

输出:

'abcd123'

答案 1 :(得分:1)

string用于列表理解

import string
whitelist = set(string.ascii_lowercase + string.digits)
name = ''.join(c for c in name if c in whitelist)

答案 2 :(得分:1)

您可以使用简单的正则表达式:

from path.config import build_db_url
from path.models import (
    Base,
    SomeTable  # Note: SomeTable inherits from Base, which is a declarative_base
)

URL = build_db_url()

# this is the Alembic Config object, which provides
# access to the values within the .ini file in use.
config = context.config

# add your model's MetaData object here
# for 'autogenerate' support
# from myapp import mymodel
# target_metadata = mymodel.Base.metadata
target_metadata = Base.metadata

def run_migrations_online():
    """Run migrations in 'online' mode.

    In this scenario we need to create an Engine
    and associate a connection with the context.

    """

    connectable = engine_from_config(
        config.get_section(config.config_ini_section),
        url=URL,
        prefix="sqlalchemy.",
        poolclass=pool.NullPool
    )

    with connectable.connect() as connection:
        context.configure(
            connection=connection,
            target_metadata=target_metadata,
            compare_server_default=True
        )

        with context.begin_transaction():
            context.run_migrations()

print(target_metadata)
run_migrations_online()

请注意,字符串是不可变的。您需要分配一个新变量才能进行更改。