简体   繁体   中英

How can I get a piece of a string between two specific characters from a string in Python

I have a Json file which I converted to a dictionary in python. One of the values called (target) in the dictionary has this string. I want to create a file with this string name (dawn_tables_tornado_affected.txt) and writing the contents from another value of the same dictionary

target = /inc/ab_sdfs_sf/dawn_tables_tornado_affected.sql

with open("/Users/David/House/“ + str(point.get('target')) + “.txt , "w") as f:
    f.write()

How can I get the variable to only use 'dawn_tables_tornado_affected' ?

There's some errors in your code

target should be a string and then wrapped in double quotes "

The character isn't valid for string closing and should be replaced by "

If you want to extract "dawn_tables_tornado_affected" from "/inc/ab_sdfs_sf/dawn_tables_tornado_affected.sql" you can use the following :

target = "/inc/ab_sdfs_sf/dawn_tables_tornado_affected.sql"

file_name = target.split('/')[-1].split('.')[0]

target.split('/') will split the string into an array using '/' as delimiter. target.split('/')[-1] gets the last item of the array.

Try this !

Python code :

import re
target = "/inc/ab_sdfs_sf/dawn_tables_tornado_affected.sql"
matchObj = re.match( r'.*/([^/]*)[.]', target, re.M|re.I)
print ("File Name : ", matchObj.group(1))

Output :

File Name :  dawn_tables_tornado_affected 

Verify through regex 101 :

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM