0

I need to remove a certain string with the given input. For example,

user_input = input("Input File name: ")

and the user key in "patient_zero[20150203].txt" and it would like to clean up the file name by removing all instances of square brackets and the contents contained within it.

Output should be "patient_zero.txt". Is there anyway to do it?

Ian
  • 199
  • 3
  • 5
  • Does this answer your question? [Python regular expression to remove all square brackets and their contents](https://stackoverflow.com/questions/42324466/python-regular-expression-to-remove-all-square-brackets-and-their-contents) – Maurice Meyer Apr 14 '21 at 15:34
  • @MauriceMeyer Maybe not, if the OP only wants to target square brackets occurring within the filename itself (but not elsewhere in the input). – Tim Biegeleisen Apr 14 '21 at 15:36

3 Answers3

2

If you just want to remove the square bracket portion of the filename, you could use:

inp = "patient_zero[20150203].txt"
output = re.sub(r'^(\S+)\[.*?\]\.(\S+)$', r'\1.\2', inp)
print(output)  # patient_zero.txt
Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360
0

using spplit

var = "patient_zero[20150203].txt"
print(var.split("[")[0] + var.split("]")[1]) # PatientName + FileFormat
Anmol Parida
  • 672
  • 5
  • 16
0
import re

s = "patient_zero[20150203].txt"

print (re.sub(r'\[[\w\s]+\]','',s))

Output:

patient_zero.txt
Synthase
  • 5,849
  • 2
  • 12
  • 34