简体   繁体   English

一行包含以','分隔的字符串

[英]a line contains strings,separated by ','

in Python, trying to do this thing: I have a line contains several strings separated by ','. 在Python中,尝试执行以下操作:我有一行包含由','分隔的几个字符串。 I want to erase every string that has particular substring in it. 我想删除其中具有特定子字符串的每个字符串。 for example: 例如:

line: first_name,second_name,every_single_name_exicted,dog,cat.

I want to erase every string that has the word "name" in it + the ',' it has, so the result would be: 我想删除其中包含单词“ name” +“'”的每个字符串,因此结果将是:

line: dog,cat.

and not: 并不是:

line: ,,,dog,cat

what can I use to achieve that? 我可以用什么来实现这一目标? and how generally can I search particular substring when I don't care what it has on its left or right (like the search option in NotePad for example when you can write name ) 以及当我不在乎某个子字符串的左侧或右侧时,如何一般搜索该子字符串(例如,当您可以输入name时,例如NotePad中的搜索选项)

s = 'first_name,second_name,every_single_name_exicted,dog,cat'

s = s.split(',')
a = ','.join([i for i in s if 'name' not in i])
print(a)

Try this 尝试这个

  • split the string with .split(",") 用.split(“,”)分割字符串
  • Filter by "name" with if not in . if not in按“名称”过滤。
  • strip leading / trailing whitespace with .strip() 使用.strip()去除前导/尾随空白
  • join the string with ", ".join() 用“,” .join()连接字符串
  • Add a dot at the end of the string if necessary with + "." 如有必要,在字符串的末尾添加一个点,并用+“。”

Like this: 像这样:

 mystring = "first_name,  second_name, every_single_name_exicted,dog,cat"

 newstring = ", ".join(s.strip() for s in mystring.split(",") if not "name" in s) + "."

暂无
暂无

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

相关问题 如何从文本文件中打印字符串,在 Python 中以新行分隔 - How to print strings from a text file,separated by new line in Python 逐行读取文件并打印包含两个不同字符串的文件 - Read file line by line and print if it contains two different strings 如何输出包含列表中任何字符串的文件中的每一行 - How to output each line in a file which contains any of the strings in a list 如何打印由一行分隔的许多预先存在的字符串? - How can I print many pre-existing strings separated by a line? 如何打印 python 字符串列表的制表符分隔值,指定最大行长度并避免字符串中断 - how to print tab separated values of a python list of strings specifying a maximum line length and avoiding string break 打印具有以“ +”分隔的字符和以“,”分隔的字符串的字符串 - Printing strings that have chars separated by “ + ” and strings themselves separated by “ , ” 在 python 中剪切以逗号分隔的字符串 - Cut strings separated by comma in python 返回由定界符分隔的字符串列表 - returning a list of strings separated by a delimiter 给定一个 string,将其偶数索引和奇数索引字符作为空格分隔的字符串打印在一行上 - Given a string, print its even-indexed and odd-indexed characters as space-separated strings on a single line Python - 删除包含特定字符串的行,而不是所有包含部分单词的字符串 - Python - Remove a line that contains a specific string not all strings containing part of word
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM