简体   繁体   中英

Aliasing str.join in python

Is it possible to alias str.join in python3 ?

For example:

a=['a','b','c']
j=str.join
''.j(a)

but also to be able to do

' '.j(a)

with the same alias or more generally to be able to use it like:

string_here.j(iterable here)

Not quite with the syntax you want, but close enough:

>>> a=['a','b','c']
>>> j=str.join
>>> j('', a)
'abc'
>>> j(' ', a)
'a b c'

str.join is an unbound method. To apply it to an object, you need to specify that object as the first argument.

TL;DR: Yes, but not in the way you expect.

In your example, you are aliasing an unbound function. What that means simply is that is has no object to apply it on implicitly, so you have to pass on a reference to which object the operations are to be performed on.

This is what the self argument in methods is for. Normally you have it automatically passed for you when you use the `. style notation, but here you have to provide it explicitly.

>>> list_ = [1, 2, 3]
>>> f = str.join   # aliasing the class method
>>> f(' ', list_)  # passing a reference to s
prints "1 2 3"
>>> f('', list_ )  # flexibility to use any string

If you want to be able to just say f(list_) , then the f function has to be bound. This means you have to know what string you're going to be using in advance. Here's how to do that:

>>> str_ = ' '
>>> list_ 
>>> f = str_.join   # aliasing the object method
>>> f(list_)        # no need to pass a reference now
"1 2 3"

I hope you understood what I was saying. Python is a great language and has the least gotcha's of any language. I couldn't FGITW my way into the top, but I hope you will like the comprehensive example. If you have any questions, just ask me.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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