简体   繁体   English

将两个.join方法合并为一个

[英]Combine two .join methods into one

Now I have this : 现在我有这个:

str = "  s  tr & &^ 23G7/*%45afju657**(%^#%$!!fdf"

str = ''.join(e for e in str if e.isalnum())
str = ''.join(('...', str, '...'))

Can I combine them like : 我可以将它们组合成:

str = ''.join(('...', e for e in str if e.isalnum(), '...'))

You can use format there 你可以在那里使用format

s = "...{}...".format(''.join(e for e in s if e.isalnum()))

As a side note, do not name your string as str as it shadows the builtin 作为旁注,请不要将字符串命名为str因为它会影响内置字符串

Apart from that, if you really really want to use join twice, you can write it as 除此之外,如果你真的想要使用join两次,你可以把它写成

''.join(('...', ''.join(e for e in s if e.isalnum()), '...'))

But it is not a good idea. 但这不是一个好主意。 Why use a nuclear bomb to kill a mosquito! 为什么用核弹杀死蚊子!

你能做到的

my_str = ''.join(['...']+ [e for e in my_str if e.isalnum()] +['...'])

Why don't you just use the + operator? 你为什么不只使用+运算符? And filter is also quite nice. filter也很不错。 Since you use Python 2.7, you don't even need to re-join: 由于您使用的是Python 2.7,因此您甚至无需重新加入:

>>> s = "  s  tr & &^ 23G7/*%45afju657**(%^#%$!!fdf"
>>> s = '...' + filter(str.isalnum, s) + '...'
>>> s
'...str23G745afju657fdf...'
string = "  s  tr & &^ 23G7/*%45afju657**(%^#%$!!fdf"

You can use filter() as syntactic sugar for a comprehension. 您可以使用filter()作为语法糖来理解。 It works best for functions rather than methods, however - the lambda that disguises the string method as a function makes this slow compared to the simple comprehension (thanks, @Bhargav). 它最适用于函数而不是方法,但是将字符串方法伪装成函数的lambda与简单理解(感谢@Bhargav)相比变得缓慢。

string = ''.join(['...', ''.join(filter(lambda x: x.isalnum(), string)), '...'])

or: 要么:

string = ''.join(filter(lambda x: x.isalnum(), string)).join(['...']*2)

depending on what ordering you prefer. 取决于您喜欢的订单。

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

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