python 去掉单引号与双引号
时间: 2023-11-04 22:12:45 浏览: 52
可以使用字符串的 strip() 方法来去掉单引号和双引号,例如:
```python
s = "'hello' \"world\""
s = s.strip("'").strip("\"")
print(s) # 输出结果为:hello world
```
其中,strip() 方法可以去掉字符串开头和结尾的指定字符,默认去掉空格字符。所以上述代码中,先使用 strip() 方法去掉单引号,再使用 strip() 方法去掉双引号。
相关问题
python怎么去除引号
如果你想去除一个字符串中的引号,可以使用字符串的replace()方法。例如,如果你想从字符串"Hello 'World'"中去掉单引号,可以使用以下代码:
```
original_string = "Hello 'World'"
new_string = original_string.replace("'", "")
print(new_string)
```
输出结果将是:"Hello World"。
如果你想去掉双引号,可以使用类似的方法:
```
original_string = 'My name is "Alice"'
new_string = original_string.replace('"', "")
print(new_string)
```
输出结果为:"My name is Alice"。
校验网址,去除其中的单引号,双引号以及反引号
校验网址可以使用正则表达式来实现,同时可以在校验的过程中去除其中的单引号、双引号和反引号等特殊字符。以下是一个示例代码:
```python
import re
def validate_url(url):
# 去除单引号、双引号和反引号
url = url.replace("'", "").replace('"', "").replace("`", "")
# 正则表达式校验
pattern = re.compile(
r'^(?:http|ftp)s?://' # http:// or https://
r'(?:(?:[A-Z0-9](?:[A-Z0-9-]{0,61}[A-Z0-9])?\.)+(?:[A-Z]{2,6}\.?|[A-Z0-9-]{2,}\.?)|' # domain...
r'localhost|' # localhost...
r'\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})' # ...or ip
r'(?::\d+)?' # optional port
r'(?:/?|[/?]\S+)$', re.IGNORECASE)
return pattern.match(url) is not None
```
该函数首先会去除URL中的单引号、双引号和反引号,然后使用正则表达式进行校验。正则表达式可以匹配常见的URL格式,包括HTTP、HTTPS、FTP等协议,以及IP地址和域名等。如果URL格式正确,则返回True,否则返回False。