繁体   English   中英

如何从python中的字符中删除字符串?

[英]How can I remove the string from a character in python?

我有一些 URL,我需要将其中一些从问号 (?)

前任。 https://www.yelp.com/biz/starbucks-san-leandro-4?large_photo=1

我需要它返回https://www.yelp.com/biz/starbucks-san-leandro-4

我怎样才能做到这一点?

您也可以使用.split()方法

split()方法将字符串拆分为列表。

您可以指定分隔符,默认分隔符是任何空格。

句法

 string.split(separator, maxsplit) 
data = 'https://www.yelp.com/biz/starbucks-san-leandro-4?large_photo=1'
print (data.split('?')[0])

输出:

https://www.yelp.com/biz/starbucks-san-leandro-4

您可以使用rfind并将字符串切成返回的索引:

s = 'https://www.yelp.com/biz/starbucks-san-leandro-4?large_photo=1'

s[:s.rfind('?')]
# 'https://www.yelp.com/biz/starbucks-san-leandro-4'

去一个正则表达式

import re

new_string = re.sub(r'\?.+$', '', your_string)

参见regex101.com上的演示

我将解析该URL,并使用您想要保留的部分进行重建。 例如,您可以使用urllib.parse

string =“”表示我在url中:如果i!=“?”:字符串+ = i

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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