Delete all characters after a backslash in python? - python

I have a for loop that changes the string current_part.
Current_part should have a format of 1234 but sometimes it has the format of 1234/gg
Other formats exist but in all of them, anything after the backlash need to be deleted.
I found a similar example below so I tried it but it didn't work. How can I fix this? Thanks
current_part = re.sub(r"\B\\\w+", "", str(current_part))

No need for regexes here, why don't you simply go for current_part = current_part.split('/')[0] ?

Find the position of '/' and replace your string with all characters preceding '/'
st = "12345/gg"
n = st.find('/');
st = st[:n]
print(st)

You can split your string using string.split()
for example:
new_string = current_part.split("/")[0]

Related

Delete specific duplicated punctuation from string

I have this string s = "(0|\\+33)[1-9]( *[0-9]{2}){4}". And I want to delete just the duplicated just one ' \ ', like I want the rsult to look like (0|\+33)[1-9]( *[0-9]{2}){4}.
When I used this code, all the duplicated characters are removed:
result = "".join(dict.fromkeys(s)).
But in my case I want just to remove the duplicated ' \ '. Any help is highly appreciated
A solution using the re module:
import re
s = r"(0|\\+33)[1-9]( *[0-9]{2}){4}"
s = re.sub(r"\\(?=\\)", "", s)
print(s)
I look for all backslashes, that are followed by another backslash and replace it with an empty sign.
Output: (0|\+33)[1-9]( *[0-9]{2}){4}​
The function you need is replace
s = "(0|\\+33)[1-9]( *[0-9]{2}){4}"
result = s.replace("\\","")
EDIT
I see now that you want to remove just one \ and not both.
In order to do this you have to modify the call to replace this way
result = s.replace("\","",1) # last argument is the number of occurrances to replace
or
result = s.replace("\\","\")
EDIT of the EDIT
Backslashes are special in Python.
I'm using Python 3.10.5. If I do
x = "ab\c"
y = "ab\\c"
print(len(x)==len(y))
I get a True.
That's because backslashes are used to escape special characters, and that makes the backslash a special character :)
I suggest you to try a little bit with replace until you get what you need.

Remove characters from a string only when they occur in a certain order in python

I am trying to clean up this string "cha?ra\ncter num?\nber". I want it to remove "?" and "\n" without removing "n" when it is alone. I tried the following, but it doesn't work. Any advice appreciated!
data_doc='cha?ra\ncter num?\nber'
code={"?":"", "\n":""}
table=str.maketrans(code.keys())
data_doc.translate(table)
An even shorter way to do this could be to simply use replace
data_doc='cha?ra\ncter num?\nber'
data_doc = data_doc.replace('?','').replace('\n','')
Output:
character number
import re
data_doc='cha?ra\ncter num?\nber'
cleaned = re.sub("[\\n\?]", "", data_doc)
print(cleaned)
The output:
character number

How to remove text before a particular character or string in multi-line text?

I want to remove all the text before and including */ in a string.
For example, consider:
string = ''' something
other things
etc. */ extra text.
'''
Here I want extra text. as the output.
I tried:
string = re.sub("^(.*)(?=*/)", "", string)
I also tried:
string = re.sub(re.compile(r"^.\*/", re.DOTALL), "", string)
But when I print string, it did not perform the operation I wanted and the whole string is printing.
I suppose you're fine without regular expressions:
string[string.index("*/ ")+3:]
And if you want to strip that newline:
string[string.index("*/ ")+3:].rstrip()
The problem with your first regex is that . does not match newlines as you noticed. With your second one, you were closer but forgot the * that time. This would work:
string = re.sub(re.compile(r"^.*\*/", re.DOTALL), "", string)
You can also just get the part of the string that comes after your "*/":
string = re.search(r"(\*/)(.*)", string, re.DOTALL).group(2)
Update: After doing some research, I found that the pattern (\n|.) to match everything including newlines is inefficient. I've updated the answer to use [\s\S] instead as shown on the answer I linked.
The problem is that . in python regex matches everything except newlines. For a regex solution, you can do the following:
import re
strng = ''' something
other things
etc. */ extra text.
'''
print(re.sub("[\s\S]+\*/", "", strng))
# extra text.
Add in a .strip() if you want to remove that remaining leading whitespace.
to keep text until that symbol you can do:
split_str = string.split(' ')
boundary = split_str.index('*/')
new = ' '.join(split_str[0:boundary])
print(new)
which gives you:
something
other things
etc.
string_list = string.split('*/')[1:]
string = '*/'.join(string_list)
print(string)
gives output as
' extra text. \n'

Python remove everything after a space with hex \x00

I have a variable string with unknown length that has the important string at the left side and the unimportant things on the right side separated by a single space. How do I remove the unimportant information to the right?
I have tried rstrip, and split with no success.
Edit: I'll place the actual value that needs to be fixed.
"NPC_tester_contact() ) ntact() "
The very first space (the one left to the closed parenthesis) should have everything after including itself be marked as unimportant.
Edit: The output should be "NPC_tester_contact()"!
Look carefully at my string that I placed above. There is alot of whitespace after it as well. I assume that is what is causing the hiccup.
I have tried most of the solutions here and they either don't do anything or just produce whitespace.
repr(s) gives me.
'NPC_me_lvup_event_contact()\x00t()\x00act()\x00act()\x00ntact()\x00\x00\x00\x00
\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00
\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00
\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00
\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00
\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00
\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00
\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00
\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00
\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00
\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'
It should be "NPC_me_lvup_event_contact()".
Thanks!
Perhaps this is a better question. Is there a way to remove all characters after the first \x00 hex that shows up in the string?
For some reason, it works sometimes and doesn't always work. The above example was done with the method that Levon posted.
Solution: Problem solved. This is more of a null byte rather than a space byte. The solution would of been any of the below using "\x00" as the identifier instead of " ".
Thank you everyone!
UPDATE based on new string data:
Assuming s contains your string:
s.split('\x00')[0]
yields
'NPC_me_lvup_event_contact()'
split() will give you a list of strings separated by the character you specify with split. If none is specified space is used, in this case we use the hex character you are interested in.
USE split(' ')[0]
>>> a = 'aaa bbb'
>>> a.split(' ')[0]
'aaa'
>>> >
>>> mystring = 'important useless'
>>> mystring[:mystring.find(' ')]
'important'
split() w/o delimiter splits by any whitespace:
>>> "asdasd xyz".split()[0]
'asdasd'
str = "important unimportant"
important = str.split(' ')[0]
try this:
lhs,rhs=s.split() #lhs is what you want.
This only works if there is really only one space.
Otherwise, you can get lhs by (but you lose rhs):
lhs=s.split()[0]
Use the split() function, and get the first item that it returns:
raw_string = 'NPC_tester_contact() ) ntact() '
important = raw_string.split(' ')[0]
Will return:
NPC_tester_contact()
try this,
will assume that your string is stored in str
print str[0:str.index(" ")]
comment if it dont work, will solve it..
here is
My code
str = "NPC_tester_contact() ) ntact() "
print str[0:str.index(" ")]
output
NPC_tester_contact()
link
http://ideone.com/i9haI
and if you want output to be have surrounded with double-quotes then
`print '"',str[0:str.index(" ")],'"'
you could use a regex type solution also. Something like:
import re
input_string = 'NPC_me_lvup_event_contact()\x00t()\x00act()\x00act()\x00ntact()\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'
string_pat = re.compile(r'[a-zA-Z0-9\(\)_]+')
try:
first_part = string_pat.findall(input_string)[0]
except IndexError:
# There is nothing of interest for you in this string
first_part = ''

regex in python 2.4

I have a string in python as below:
"\\B1\\B1xxA1xxMdl1zzInoAEROzzMofIN"
I want to get the string as
"B1xxA1xxMdl1zzInoAEROzzMofIN"
I think this can be done using regex but could not achieve it yet. Please give me an idea.
st = "\B1\B1xxA1xxMdl1zzInoAEROzzMofIN"
s = re.sub(r"\\","",st)
idx = s.rindex("B1")
print s[idx:]
output = 'B1xxA1xxMdl1zzInoAEROzzMofIN'
OR
st = "\B1\B1xxA1xxMdl1zzInoAEROzzMofIN"
idx = st.rindex("\\")
print st[idx+1:]
output = 'B1xxA1xxMdl1zzInoAEROzzMofIN'
Here is a try:
import re
s = "\\B1\\B1xxA1xxMdl1zzInoAEROzzMofIN"
s = re.sub(r"\\[^\\]+\\","", s)
print s
Tested on http://py-ide-online.appspot.com (couldn't find a way to share though)
[EDIT] For some explanation, have a look at the Python regex documentation page and the first comment of this SO question:
How to remove symbols from a string with Python?
because using brackets [] can be tricky (IMHO)
In this case, [^\\] means anything but two backslashes \\.
So [^\\]+ means one or more character that matches anything but two backslashes \\.
If the desired section of the string is always on the RHS of a \ char then you could use:
string = "\\B1\\B1xxA1xxMdl1zzInoAEROzzMofIN"
string.rpartition("\\")[2]
output = 'B1xxA1xxMdl1zzInoAEROzzMofIN'

Categories