2016-04-21 108 views
-1

我有以下格式弦數:替換標籤中字符串元素

string = http://1.8.1.1:5000/student/<studentid>/student_details/<rollnumber> 

和2個變量

x="myid" 
y="myrollnumber" 

我要的是替換的< 1實例...>與變量x和第二個實例< ....>與變量y。它不應該取決於我在<>標籤中。任何具有該格式的字符串都應該用x和y替換它們各自的位置。輸出的結果應該是這樣的:

string=http://1.8.1.1:5000/student/myid/student_details/myrollnumber 
+0

您是否嘗試過的東西或者你只是尋找一個簡單的解決方案? – rakwaht

回答

2

你可以做這樣的,

>>> S = 'http://1.8.1.1:5000/student/<studentid>/student_details/<rollnumber>' 
>>> import re 
>>> k = re.sub(r'<.*?>', '{}', S) 
>>> k 
'http://1.8.1.1:5000/student/{}/student_details/{}' 
>>> x="myid" 
>>> y="myrollnumber" 
>>> k.format(x, y) 
'http://1.8.1.1:5000/student/myid/student_details/myrollnumber' 
>>> 
2

我不知道如果我理解正確的,但是這可能是一個解決辦法:

string = "http://1.8.1.1:5000/student/%s/student_details/%s"%(x,y) 

讓我們把它放在一個函數裏面:

def foo(studentID, rollNumber): 
    string = "http://1.8.1.1:5000/student/%s/student_details/%s"%(studentID, rollNumber) 
    return string 

這對您有幫助嗎? 讓我知道...

0

您可以使用replace

string = "http://1.8.1.1:5000/student/<studentid>/student_details/<rollnumber>" 
x="myid" 
y="myrollnumber" 

newString = string.replace("<studentid>",x).replace("<rollnumber>",y) 

在功能:

def changeString(studentid,rollNumber): 
    newString = string.replace("<studentid>",studentid).replace("<rollnumber>",rollNumber) 
    return newString