This question already has answers here:
Best way to replace multiple characters in a string?
(16 answers)
How to replace two things at once in a string?
(6 answers)
Closed 3 years ago.
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?
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
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.
Related
This question already has answers here:
How do I reverse a string in Python?
(19 answers)
Closed last year.
for example I entered follwoing string ;
" hello I am Mohsen" ;
now I want to Print on output :
"Mohsen am I hello "
please help me !
Both Corralien's and Tobi208's works, and can be combined to the shorter version;
s = "hello I am Mohsen"
print(' '.join(s.split(' ')[::-1]))
or if you want to input the string in the terminal as a prompt;
s = input()
print(' '.join(s.split(' ')[::-1]))
Split by space, reverse the list, and stitch it back together.
s = " hello I am Mohsen"
words = s.split(' ')
words_reversed = words[::-1]
s_reversed = ' '.join(words_reversed)
print(s_reversed)
This question already has answers here:
How do I escape curly-brace ({}) characters in a string while using .format (or an f-string)?
(23 answers)
Closed 2 years ago.
I know how to use string format in python
"name = {fname}".format(fname = "John")
The output is name = John
But how can I use if I need to input {} inside the string that not belong to variable , for example
"{NOTVAR} name = {fname}".format(fname = "John")
I want to output will be {NOTVAR} name = John
print("{{NOTVAR}} name = {fname}".format(fname="John"))
Output
{NOTVAR} name = John
Try
"{{NOTVAR}} name = {fname}".format(fname = "John")
Probably the simplest way is to seperate it with a +.
Something like this:
print("{NOTVAR }" + "name = {fname}".format(fname = "John"))
{NOTVAR} name = John
This question already has answers here:
How to remove all characters after a specific character in python?
(10 answers)
Closed 3 years ago.
I am trying to delete characters after "#" in an email address using python. I found some tips online but it didn't provide the exact solution I am looking for.
The whole email address I'm working on is coming from a parameter value.
paramater = [0] #contains the email address i.e. testing#email.com
mainStr = parameter [0]
newstring = mainStr.replace('#' , ' ')
Obviously, the above code is not providing me with result I am expecting which is to delete all strings after #.
in = 'test#gmail.com'
out = s.split('#')[0]
or
out = ''.join(re.findall('(.*)#',s))
With regex
import re
re.sub(r'#.*', '', 'test#email.com')
I don't know your code.
But, I write code by my way.
s = test#email.com
end = s.find('#')
s[:end]
Do you want a part of account? ( for example " testing" in "testing#baba.net")
Then
exampleString = "testing#baba.net"
indexOfAt = exampleString.find("#") # get index of #
print (indexOfAt)
accountPart = exampleString[:indexOfAt]
print (accountPart)
the result is as follows
7
testing
This question already has answers here:
How to find index of an exact word in a string in Python [duplicate]
(5 answers)
Closed 5 years ago.
I need to find the starting index of a string when there is an exact match to a sub-string.
line = "Your family and You are invited to my party"
I want to find the starting index of Youi.e. 16
I have tried
line.find("You")
however that returns 0
Then I tried,
import re
print(re.findall('\\bYou\\b', line))
But it returns a list with the sub-string in it
["You"]
If you are fine using a regex then this answer should address your issue.
Applying that to your question. We get
import re
a = re.search(r'\b(you)\b', 'Your family and you are invited to the party')
print a.start()
Which gives 16
Does this work for all possible positions of "you"? (start, middle and end)? Let's check
str1 = "you hi"
str2 = "hi you"
str3 = "hi you hi"
re.search(r'\b(you)\b', str1).start()
# output is 0
re.search(r'\b(you)\b', str2).start()
# output is 3
re.search(r'\b(you)\b', str3).start()
# output is 3
UPDATE 1: Case insensitive matching
In case you want a case insensitive match use re.IGNORECASE like this
re.search(r'\b(you)\b', str3, re.IGNORECASE).start()
UPDATE 2: Passing a variable instead of hardcoded string in the regex
str = "Your family and you are invited to the party"
word_to_search = "you"
re_string = r"\b({})\b".format(word_to_search)
re.search(re_string, str).start()
#output is 16
This Should work
import re
line = "Your family and You are invited to my party"
re.search('\\bYou\\b', line).start()
to get the exact index
Use re.search to get appropriate position of your pattern.
For example:
import re
line = "Your family and You are invited to my party"
res = re.search('\\bYou\\b', line)
It gives a result that looks like
<_sre.SRE_Match object; span=(16, 19), match='You'>
Then
beg, end = res.span()
where variable beg stores required index.
This question already has answers here:
Check if multiple strings exist in another string
(17 answers)
Closed 5 years ago.
I'm new to coding, and am wondering if there is a way to simplify this:
if "!" in name or "$" in name or "%" in name or "^" in name or "&" in name or "*" in name or "(" in name or ")" in name or "_" in name or "-" in name or "+" in name or "=" in name:
points = points + 1
Thank you
You can use regex:
import re
if re.findall('[\!\$\%\^\&\*\_\-\+\=]', name):
points += 1
chars = set("!$%^&*()_-+=")
if any((i in chars) for i in string):
points += 1
You can write a simple function to achieve this.
def is_included(characters, sentence):
for character in characters:
if character in sentence:
return True
return False
As mgilson mention you can use any keyword too. However since you are new to programming I suggest you to learn the algorithms of keywords.