#!/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()
我在 test.py 文件中有上面的代码,当我运行这段代码并将我的选择作为 SECONDARY 时,我得到的输出是 SECONDARY 作为字符串:
[oracle@localhost oracle]$ ./test.py
输入您的选择 [PRIMARY|SECONDARY]: SECONDARY
中学
我想将前缀添加为“^”,将后缀添加为“$”以添加到我的输出中。这应该只是一个字符串。意味着我想得到输出:
^中学$
请告诉我如何实现这一目标。
最佳答案
您可以使用 + 将它们连接到字符串上。
例如(对于 Python 2):
print "^"+str1+"$"
或者不使用 + 在 Python 3 中使用 f-strings:
print( f“^{str}$” )
或者如果你想为列表中的每个字符串添加前缀:
strings = ['hello', 1, 'bye']
decoratedstrings = [f"^{s}$" for s in strings]
结果:
['^hello$', '^1$', '^bye$']
https://stackoverflow.com/questions/33941341/