python - 除非在引号之间找到空格,否则使用空格作为分隔符在python中拆分字符串
问题描述
我想使用空格作为分隔符来拆分文本,除非在引号之间找到空格
例如
string = "my name is 'solid snake'"
output = ["my","name","is","'solid snake'"]
解决方案
遍历字符串:
string = "my name is 'solid snake'"
quotes_opened = False
out = []
toadd = ''
for c, char in enumerate(string):
if c == len(string) - 1: #is the character the last char
toadd += char
out.append(toadd); break
elif char in ("'", '"'): #is the character a quote
if quotes_opened:
quotes_opened = False #if quotes are open then close
else:
quotes_opened = True #if quotes are closed the open
toadd += char
elif char != ' ':
toadd += char #add the character if it is not a space
elif char == ' ': #if character is a space
if not quotes_opened: #if quotes are not open then add the string to list
out.append(toadd)
toadd = ''
else: #if quotes are still open then do not add to list
toadd += char
print(out)
推荐阅读
- javascript - 映射 ListItem,复选框仅更改一行(React Native)
- excel - 合并重叠日期并查找多个唯一 ID 的不重叠
- vue.js - 如何为多租户项目的 API 设置 axios 基础 URL?
- c# - 删除边距/DwmExtendFrameIntoClientArea (C#)
- angular - Angular 开发通过 IP 地址代理 Web 套接字失败
- flutter - 有没有办法在 Flutter 的应用栏操作按钮后面添加阴影?
- javascript - React Router 在单独的页面上渲染组件
- azure-cosmosdb - 对 cosmosDB 中的唯一键约束强制执行不区分大小写的值?
- c++ - 在 C++ 中使用 getline 从文件中读取
- java - 如何在 Java 中检测和防止内存泄漏