#!/usr/bin/python
import sys,re
import subprocess
def funa():
a = str(raw_input('Enter your choice [PRIMARY|SECONDARY]: ')).upper().strip()
p = re.compile(r'.*'+a+'.*')
result = p.findall(a)
str1 = ''.join(result)
print str1
funa()
Run Code Online (Sandbox Code Playgroud)
我在 test.py 文件中有上面的代码,当我运行此代码并选择 SECONDARY 时,我得到的输出 SECONDARY 作为字符串:
[oracle@localhost oracle]$ ./test.py
Enter your choice [PRIMARY|SECONDARY]: SECONDARY
SECONDARY
我想添加前缀“^”和后缀“$”以添加到我的输出中。这应该只是一个字符串。意味着我想得到的输出为:
^中学$
请让我知道如何实现这一目标。
您可以使用 + 将它们连接到字符串上。
\n例如(对于 Python 2):
\nprint "^"+str1+"$"\nRun Code Online (Sandbox Code Playgroud)\n或者在 Python 3 中不使用 + 使用 f 字符串:
\nprint( f\xe2\x80\x9c^{str}$\xe2\x80\x9d )\nRun Code Online (Sandbox Code Playgroud)\n或者,如果您想为列表中的每个字符串添加前缀:
\nstrings = ['hello', 1, 'bye']\ndecoratedstrings = [f"^{s}$" for s in strings]\nRun Code Online (Sandbox Code Playgroud)\n结果:
\n['^hello$', '^1$', '^bye$']\nRun Code Online (Sandbox Code Playgroud)\n