python - 如何在python中为字符串添加前缀和后缀

#!/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/

相关文章:

git - "git clone"是否创建一个完全相对的目录?

java - 当新阶段弹出时,我如何禁用初级阶段

cordova - react 路由器和 Cordova 不工作

rx-java - 将热 Observable 转换为冷 Observable

solr - 使用身份验证在控制台中创建 Solr 核心

c# - wpf - Expander 的标题适合内容宽度?

css - 输入内的响应式 fa-icon

php - 使用 Prestashop 1.6 在模块中获取产品类别名称

php - 编译PHP7错误

c# - 还有其他更好的方法可以将参数传递给 backgroundworker runasync 吗