简体   繁体   English

用于读取csv字符串中第n个元素的Python代码

[英]Python code for reading nth element in a csv string

I am new to python and i have a variable containing a csv string and i want to be able to read specific elements of that string. 我是python的新手,我有一个包含csv字符串的变量,我希望能够读取该字符串的特定元素。 all the searches to day on this topic refer to multi row csv files. 关于此主题的所有搜索都涉及多行csv文件。 I am simply seeking the correct code to read the value from a variable containing the single csv string not a file 我只是在寻找正确的代码来从包含单个csv字符串而不是文件的变量中读取值

The following code: 以下代码:

delimiter=','
position=2
row='foo,bar,baz,googoo'
print(row.split(delimiter)[position])

Will output (as index 0 is 'foo'): 输出(因为索引0是'foo'):

baz

I did not quite understand what specific elements you are interested in 我不太明白你感兴趣的具体元素

If you are looking for elements based on the position 如果您正在寻找基于位置的元素

   csv_row="test1,test2,test3,test4,test5,test6"
   print(csv_row.split(",")[<position>]

If you want to find if an element exists in the CSV and get the position of it 如果要查找CSV中是否存在元素并获取其位置

   csv_row="test1,test2,test3,test4,test5,test6"
   csv_list=csv_row.split(",")
   if 'test1' in csv_list:
      print(csv_list.index('test1'))

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

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