【问题标题】:How To Separate & Store Strings Into Variables From a CSV Line Using Python?如何使用 Python 将字符串从 CSV 行中分离并存储到变量中?
【发布时间】:2017-03-09 01:12:04
【问题描述】:

例如,如何从 CSV 行中分离和存储字符串;

我有这个字符串:

data = "product name, description, weight, shipping dest"

我想像这样保存到 python 变量中:

a = "product name"
b = "description"
c = "weight"
d = "shipping dest"

提前致谢!

【问题讨论】:

  • 如果它是一个 csv 文件,你应该使用 csv 模块。可能有很多 SO 答案展示了如何做到这一点,所以我不会重复它们。
  • 对不起,它不是一个 CSV 文件,只是从以逗号分隔的条形码接收到的字符串。

标签: python string csv


【解决方案1】:

使用字符串的拆分功能:

data = "product name, description, weight, shipping dest"
a, b, c, d = data.split(', ')

这是它的 Python 2.7 参考:https://docs.python.org/2/library/stdtypes.html#str.split

这里是 Python 3 的参考: https://docs.python.org/3.5/library/stdtypes.html#str.split

【讨论】:

  • 谢谢!正是我想要的,python 中的某种分隔符。
  • 太棒了,很高兴我能帮上忙。如果它解决了你的问题,你能接受它作为答案吗?
猜你喜欢
  • 1970-01-01
  • 2015-12-27
  • 1970-01-01
  • 2014-07-27
  • 2020-07-31
  • 2015-10-21
  • 2013-09-23
  • 1970-01-01
  • 2015-02-05
相关资源
最近更新 更多