Python-删除变量字符串中的ASCII引号
我正在尝试使用ascii转换插入变量字符串:Python-删除变量字符串中的ASCII引号,python,string,python-3.x,Python,String,Python 3.x,我正在尝试使用ascii转换插入变量字符串: strings = ['a','b'] for string in strings: print ('print this: %a, and be done' % (string)) 这张照片 print this: 'a', and be done print this: 'b', and be done 但是我不希望引号(')出现在字符串中。有没有一种简单的方法可以移除?我希望输出如下: print this: a, and be
strings = ['a','b']
for string in strings:
print ('print this: %a, and be done' % (string))
这张照片
print this: 'a', and be done
print this: 'b', and be done
但是我不希望引号(')出现在字符串中。有没有一种简单的方法可以移除?我希望输出如下:
print this: a, and be done
print this: b, and be done
注意,我需要继续为我的用例使用%a方法。无法切换到{}.format方法 旧的
%
格式笨重且难以使用。考虑切换到使用<代码>格式> <代码>方法,如下所示:
strings = ['a', 'b']
for string in strings:
print('print this: {}, and be done'.format(string))
这将根据需要插入string
的str
表示形式。如果您有Python3.6,您甚至可以使用文字版本
strings = ['a', 'b']
for string in strings:
print(f'print this: {string}, and be done')
旧的
%
格式笨重且难以使用。考虑切换到使用<代码>格式> <代码>方法,如下所示:
strings = ['a', 'b']
for string in strings:
print('print this: {}, and be done'.format(string))
这将根据需要插入string
的str
表示形式。如果您有Python3.6,您甚至可以使用文字版本
strings = ['a', 'b']
for string in strings:
print(f'print this: {string}, and be done')
您可以使用
unicode转义编码
并解码回字符串:
hex_escaped = string.encode('unicode-escape').decode('ascii')
print('print this: %s, and be done' % (hex_escaped,))
您可以使用
unicode转义编码
并解码回字符串:
hex_escaped = string.encode('unicode-escape').decode('ascii')
print('print this: %s, and be done' % (hex_escaped,))
因此,您希望
%s
而不是%a
?通常是的,但我希望ASCII转换保持不变。“ASCII转换”例如从内置类型页(),%s使用str()函数转换,%a使用ASCII()函数转换。我需要一个ascii输出。因此您想要%s
而不是%a
?通常是的,但我希望ascii转换保持不变。“ascii转换”例如?从内置类型页(),%s使用str()函数转换,%a使用ascii()函数转换。我需要ascii输出。请参阅上面的注释,python需要使用ascii函数进行转换。@Jeffsalt首先请注意,ascii()
的输出是unicodestr
,而不是字节
。如果上述方法对您来说还不够,请详细说明您希望代码执行的操作。我希望输出为unicode字符串,但字符串周围不包含(')。{}.format方法对我当前的任务不起作用。基本上,我只是想弄清楚如何在仍然使用%a的情况下删除变量字符串周围的“,”,然后您可以执行print(“…”+(“%a”%string)[1:-1]+“…”)
,但这太傻了。请参阅上面的注释,需要python使用ascii函数进行转换。@请注意,ascii()
的输出是unicodestr
,而不是字节。如果上述方法对您来说还不够,请详细说明您希望代码执行的操作。我希望输出为unicode字符串,但字符串周围不包含(')。{}.format方法对我当前的任务不起作用。基本上,我只是想弄清楚如何在仍然使用%a的情况下删除变量字符串周围的“,”,然后可以执行print(“…”+(“%a”%string)[1:-1]+“…”)
,但这很愚蠢。这看起来很有趣,将进行测试。@JeffSaltfist:是否希望在出现“
时对进行转义?这看起来很有趣,将进行测试。@JeffSaltfist:是否希望在出现”
时对进行转义?