0

I have text file with the following content:

Hi, my name is 'James'. What is your [name]

I wont to remove the ' ' and the [] from the text so the output looks like this:

Hi, my name is James. What is your name

Here is my code:

s=  Hi, my name is 'James'. What is your [name]
s=s.replace("[","")
s=s.replace("'","")

However the output leave a bracket to the right of name:

Hi, my name is James. What is your name] 

Any ideas?

James Davinport
  • 303
  • 7
  • 19

2 Answers2

1

You forgot to replace ] in your original code. You can also chain replace statements together

In [2]: s=  "Hi, my name is 'James'. What is your [name]"                                                                                                                              

In [3]: s = s.replace("'",'').replace("[","").replace("]","")                                                                                                                          

In [4]: s                                                                                                                                                                              
Out[4]: 'Hi, my name is James. What is your name'

Or you can use a regex to strip of [] and ' using the regex [\[\]\'], which essentially replaces the characters []' when found in the string with an empty character using re.sub

import re

s = "Hi, my name is 'James'. What is your [name]"
out = re.sub(r"[\[\]\']", "",s)
print(out)

The output will be

Hi, my name is James. What is your name
Devesh Kumar Singh
  • 20,259
  • 5
  • 21
  • 40
-2

if your trying to just put this in console or terminal then print("Hi, my name is James. What is your name? ") will work just fine But if you are looking for a person to 'talk' and respond then use an input like, input('Hi, my name is James. What is your name ') the user can then type after this and if you use a variable you can respond to the users response example

name = input('whats your name'? ) print('Hi' + name + 'How are you'? )

putting spaces after question marks will make the code look better(in my opinion) when being executed.

  • ps. you put wont instead of want – Timothy Rice May 30 '19 at 17:33
  • He never uses an `input` so why would you assume he controls the user input? Most commonly people who ask questions like this are reading data from a static source (such as a file, api, or database). As such just say ("Well don't input that") is not a very good answer. – Error - Syntactical Remorse May 30 '19 at 17:56
  • i wasn't telling him to input it was a question i asked if he was tring to get an input or simply printing the sentence i'm sorry if i didn't make that clear – Timothy Rice May 30 '19 at 22:14