簡體   English   中英

如何從 Python 中的字符串中獲取兩個特定字符之間的一段字符串

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

我有一個 Json 文件,我在 python 中將其轉換為字典。 字典中稱為 (target) 的值之一具有此字符串。 我想用這個字符串名稱(dawn_tables_tornado_affected.txt)創建一個文件,並從同一字典的另一個值中寫入內容

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()

我怎樣才能讓變量只使用 'dawn_tables_tornado_affected' ?

您的代碼中有一些錯誤

目標應該是一個字符串,然后用雙引號括起來"

字符對於字符串結束無效,應替換為"

如果您想從"/inc/ab_sdfs_sf/dawn_tables_tornado_affected.sql"提取"dawn_tables_tornado_affected" ,您可以使用以下命令:

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

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

target.split('/')將使用'/'作為分隔符將字符串拆分為一個數組。 target.split('/')[-1]獲取數組的最后一項。

嘗試這個 !

蟒蛇代碼:

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))

輸出 :

File Name :  dawn_tables_tornado_affected 

通過正則表達式 101 驗證:

在此處輸入圖片說明

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM