python中split去除空串
时间: 2023-11-20 10:52:26 浏览: 60
在Python中,split()函数可以通过指定分隔符对字符串进行切片,并返回分割后的字符串列表。但是在默认情况下,split函数会将分割后的字符串中的空字符串也添加到列表中。如果我们不需要这些空字符串,就需要再进行一次去空操作。可以使用strip()函数从字符串的开头和结尾删除空格,然后再使用列表推导式将每个元素中的首尾空字符串去除。具体实现如下:
str = "https://www.baidu.com/"
str_list = str.split('/')
print("原始列表:" + str(str_list))
new_list = [x.strip() for x in str_list if x.strip()]
print("去除空串后列表:" + str(new_list))
这样就可以得到去除空串后的列表了。
相关问题
sprin项目中请求参数拦截去空串
在Spring项目中,可以使用拦截器对请求参数进行拦截,进而过滤空字符串。你可以实现自定义的拦截器,继承HandlerInterceptorAdapter,并覆写其中的preHandle方法。
例如:
```java
public class EmptyParamInterceptor extends HandlerInterceptorAdapter {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
Enumeration<String> parameterNames = request.getParameterNames();
while (parameterNames.hasMoreElements()) {
String key = parameterNames.nextElement();
String value = request.getParameter(key);
if (StringUtils.isEmpty(value)) {
request.setAttribute("errorMsg", key + "不能为空!");
request.getRequestDispatcher("/error-page").forward(request, response);
return false;
}
}
return true;
}
}
```
在该拦截器中,我们首先获取所有的请求参数名,然后判断其对应的参数值是否为空。如果为空,我们使用request.setAttribute将错误信息添加到request中,再将请求转发到错误页面。如果请求中存在空值,则返回false,表示拦截该请求;否则返回true,表示放行该请求。需要注意的是,在拦截器中对请求进行修改后,需要将该请求转发到正确的处理页面。
使用stream清除List<String>中的空串
可以使用 Java 8 中的 Stream 对 List<String> 进行处理,实现清除其中的空串。具体代码如下:
```java
List<String> list = Arrays.asList("a", "", "b", "", "c", "");
List<String> result = list.stream()
.filter(str -> !str.isEmpty())
.collect(Collectors.toList());
System.out.println(result);
```
输出结果为:`[a, b, c]`
首先将 List 转换成 Stream,然后使用 `filter` 方法过滤掉空串,最后使用 `collect` 方法将过滤后的结果转换成 List。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://img-home.csdnimg.cn/images/20210720083646.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)