Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add prefix and suffix to a string in python

Tags:

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()

I have above code in test.py file and When I run this code and give my choice as SECONDARY, I am getting the output SECONDARY as string:

[oracle@localhost oracle]$ ./test.py Enter your choice [PRIMARY|SECONDARY]: SECONDARY SECONDARY

I want to add prefix as '^' and suffix as '$' to add in my output. Which should be a string only. Means I want to get the output as :

^SECONDARY$

Please let me know how can I achieve this.

like image 561
Rishab Avatar asked Aug 31 '25 22:08

Rishab


1 Answers

You can concatenate those onto the string using +.

For example (for Python 2):

print "^" + str1 + "$"

Or without + using f-strings in Python 3:

print(f"^{str}$")

Or if you want to add a prefix to every string in a list:

strings = ['hello', 1, 'bye']
decoratedstrings = [f"^{s}$" for s in strings]

result:

['^hello$', '^1$', '^bye$']
like image 76
DisappointedByUnaccountableMod Avatar answered Sep 14 '25 12:09

DisappointedByUnaccountableMod



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!