How to add prefix and suffix to a string in python
23,267
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$']
Author by
Rishab
Updated on July 09, 2022Comments
-
Rishab almost 2 years
#!/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.
-
khelwood over 8 yearsYou are already using
+
on strings earlier in your function. What is it you're having trouble with?
-
-
Rishab over 8 years@barny thanks it worked for me. Not sure why its downgrade.
-
Bhargav Rao over 8 yearsThough I did not downvote, I guess the downvoter expects a bit of explanation about the code, something other than try this.
-
DisappointedByUnaccountableMod almost 3 yearsRather than
map()
andlambda
, wouldn't it be simpler to use a comprehension likestrings=[f"^{s}$" for s in strings]
?