我有一堆地址:
123 Main Street, PO Box 345, Chicago, IL 92921
1992 Super Way, Bakersfield, CA
234 Wonderland Lane, Attn: Daffy Duck, Orlando, FL 09922
当我对每个字符串myStr.split(',')
时,我怎么能在那里剪掉第二个字符串?
我的想法是想要回归:
123 Main Street, Chicago, IL 92921
1992 Super Way, CA
234 Wonderland Lane, Orlando, FL 09922
我可以遍历每个部分,并构建另一个字符串,跳过第二个索引,但是想知道是否有更好的方法。
我现在拥有的:
def filter_address(address):
print("Filtering address on",address)
updated_addr = ""
indx = 0
for section in address.split(","):
if indx != 1:
updated_addr = updated_addr + "," + section
indx += 1
updated_addr = updated_addr[1:] # This is to remove the leading `,`
new_address = filter_address("123 Main Street, Chicago, IL 92921")
答案 0 :(得分:3)
你可以在python中使用del
并在分割后用“,”将字符串的组件粘合回来。
例如:
address = "123 Main Street, PO Box 345, Chicago, IL 92921".split(",")
del address[1]
pretty_address = ", ".join(address)
print(pretty_address) # Gives 123 Main Street, Chicago, IL 92921