Python - remove parts of a string

时间:2015-05-12 22:52:32

标签: python regex string

I have many fill-in-the-blank sentences in strings,

e.g. ==

How can I efficiently parse this string (in Python) to be

"6d) We took no [pains] to hide it ."

I also would like to be able to store the word in brackets (e.g. "pains") in a list for use later. I think the regex module could be better than Python string operations like split().

5 个答案:

答案 0 :(得分:3)

This will give you all the words inside the brackets.

import re

s = '6d) We took no [pains] to hide it .'
m = re.search(r"(.*\))(.+)\[(.+)\](.+)", s)

print(m.group(2) + m.group(4)) # "We took no  to hide it ."
print(m.group(3))              # pains

Then you can run this to remove all bracketed words.

import re
s="6d) We took no [pains] to hide it ."
matches = re.findall('\[(.*?)\]', s)

答案 1 :(得分:2)

just for fun (to do the gather and substitution in one iteration)

Map("token" -> Seq(12345), 
    "userPreferences[0]" -> Seq(key1, value1, key2, value2), 
    "userPreferences[1]" -> Seq(key2, value2))

答案 2 :(得分:1)

mysqlimport                             \
 --verbose                              \
 --replace                              \
 --ignore-lines=1                       \
 --fields-terminated-by=','             \
 --fields-optionally-enclosed-by='\"'   \
 --lines-terminated-by='\n'             \
 --local                                \
 -u root -p bustracker                  \
 routes.dat

Output

import re

s = 'this is [test] string'
m = re.search(r"\[([A-Za-z0-9_]+)\]", s)
print m.group(1)

答案 3 :(得分:0)

For your example you could use this regex:

    {if $custom_field1}
        {if isset($custom_field1) && $custom_field1}
            <div>{$custom_field1}</div>
    {/if}
    {if $custom_field2}
        {if isset($custom_field2) && $custom_field2}
            <div>{$custom_field2}</div>
    {/if}

You will get four groups that you can use to create your resulting string and save the 3. group for later use:

  1. (.*\))(.+)\[(.+)\](.+)
  2. 6d)
  3. We took no
  4. pains

I used to hide it . here because I don't know if your strings always look like your example. You can change the .+ to alphanumeric or sth. more special to your case.

.+

答案 4 :(得分:0)

(b==true)

Output :

We took no to hide it .