如何在给定参数 (Python) 之前的第 N 个字符处拆分字符串
How can I split a string on the Nth character before a given parameter (Python)
通常我使用 .split() 方法在数据帧上拆分字符串,但这次我有一个如下所示的字符串:
“3017381ª 意甲 - 新兴市场”
要么
“3017381º Ano - Iniciais”
我想找到“º”或“ª”,然后将其拆分为 2 个字符。拆分后的字符串应如下所示:
["301728","1ª 意甲 - 新兴市场"]
您可以使用 str.find 函数,并更改您收到的字符串中的位置。
在一个函数中它看起来像这样(请考虑它会在 charList 中定义的选项的第一个条目上拆分字符串,但如果需要进行多次拆分,您可以扩展该方法):
def splitString(s,offset=0,charList=[]):
for opt in charList:
x = s.find(opt)
if x != -1: # default when not found
return [s[:x+offset],s[x+offset:]]
return [s] # input char not found
然后您可以调用函数:
splitString("3017381ª Série - EM",offset=-1,charList=[ "º","ª"])
可能有点乱,但结果就是你想要的。
a = "3017381ª Série - EM"
print(a[7])
print(a[5])
b = a[7]
c = a[5]
print(b)
print(c)
x = a.split(b)
y = a.split(c)
newY = y[1]
newX = x[0]
print(newY)
print(newX)
minusX = newX[:-1]
print(minusX)
z =[]
z.append(minusX)
z.append(y[1])
print("update:", z)
通常我使用 .split() 方法在数据帧上拆分字符串,但这次我有一个如下所示的字符串:
“3017381ª 意甲 - 新兴市场”
要么
“3017381º Ano - Iniciais”
我想找到“º”或“ª”,然后将其拆分为 2 个字符。拆分后的字符串应如下所示:
["301728","1ª 意甲 - 新兴市场"]
您可以使用 str.find 函数,并更改您收到的字符串中的位置。
在一个函数中它看起来像这样(请考虑它会在 charList 中定义的选项的第一个条目上拆分字符串,但如果需要进行多次拆分,您可以扩展该方法):
def splitString(s,offset=0,charList=[]):
for opt in charList:
x = s.find(opt)
if x != -1: # default when not found
return [s[:x+offset],s[x+offset:]]
return [s] # input char not found
然后您可以调用函数:
splitString("3017381ª Série - EM",offset=-1,charList=[ "º","ª"])
可能有点乱,但结果就是你想要的。
a = "3017381ª Série - EM"
print(a[7])
print(a[5])
b = a[7]
c = a[5]
print(b)
print(c)
x = a.split(b)
y = a.split(c)
newY = y[1]
newX = x[0]
print(newY)
print(newX)
minusX = newX[:-1]
print(minusX)
z =[]
z.append(minusX)
z.append(y[1])
print("update:", z)