简体   繁体   English

如何使用python仅打印一行中的某些字符

[英]How to print only certain characters from a line using python

For example, I have:例如,我有:

a = (b ^ c) || d && e

I want it to print only我只想打印

^ || &&  

I am new to python.我是python的新手。 Could someone help me with this?有人可以帮我解决这个问题吗?

We can filter out the unwanted characters with filter :我们可以过滤掉与不想要的字符filter

>>> a = "(b ^ c) || d && e"
>>> print(*filter(lambda x: not x.isalpha() and x not in '()', a), sep='')
 ^  ||  &&

Or, if you don't want multiple spaces or leading/trailing spaces:或者,如果您不想要多个空格或前导/尾随空格:

>>> print(''.join(filter(lambda x: not x.isalpha() and x not in '()', a)).replace('  ',' ').strip())
^ || &&

您可以按不需要的字符组拆分字符串,然后继续连接和去除空间:

' '.join(re.split(r'[\s\d\w()]+', a)).strip() # remove numbers, letters, and whitespace

Edit1编辑1

To correct misunderstanding I can suggest use regexp for this.为了纠正误解,我建议为此使用正则表达式。

import re
print(re.sub(r"[^\^|\|\||\&\&]", "", a))

Edit2编辑2

Comments for code above.上面代码的注释。

re.sub() function replaces by second parameter all tokens that match given pattern. re.sub()函数用第二个参数替换所有匹配给定模式的标记。 Quick training you can pass here regexone.com您可以在此处通过regexone.com 的快速培训

That part of code finds all yours symbols using given regex and replaces them by empty string.这部分代码使用给定的正则表达式查找您的所有符号,并用空字符串替换它们。

r"[^\^|\|\||\&\&]"

That regex has a folowing parts该正则表达式有以下部分

[^] - that tells find all symbols that not between [ and ]. [^] - 告诉查找所有不在 [ 和 ] 之间的符号。 ^ symbol used for negation. ^ 用于否定的符号。

\\^\\^ - your ^^ symbols shielded using backslashes \\^\\^ - 您的 ^^ 符号使用反斜杠屏蔽

\\|\\| \\|\\| - your || - 你的 || symbols符号

\\&\\& - your && symbols \\&\\& - 你的 && 符号

All of them grouped using "or" statement ( "|" symbol )所有这些都使用“或”语句(“|”符号)分组

In the end you have最后你有

^^ | ^^ | || || | | && without backslashes tells, find ^^ or || && 没有反斜杠告诉,找到 ^^ 或 || or &&或者 &&

and in [^ ^^ |并在 [^ ^^ | || || | | &&], finds every symbol that not ^^ or || &&],找出所有不是 ^^ 或 || 的符号or &&或者 &&

But if you coding at first time, or you don't know python syntax yet, i recommend you just learn python at simplest examples, and after that learn regex syntax.但是如果你是第一次编码,或者你还不知道 python 语法,我建议你只在最简单的例子中学习 python,然后学习正则表达式语法。

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

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