如何连接Object字符串(原始)而不重载和显式类型cast(str())?
class Foo:
def __init__(self, text):
self.text = text
def __str__(self):
return self.text
_string = Foo('text') + 'string'
Run Code Online (Sandbox Code Playgroud)
输出:
Traceback (most recent call last):
File "test.py", line 10, in <module>
_string = Foo('text') + 'string'
TypeError: unsupported operand type(s) for +: 'type' and 'str'
Run Code Online (Sandbox Code Playgroud)
运营商+必须超载?还有其他方式(只是想知道)?
PS:我知道重载运算符和类型转换(如str(Foo('text')))
我知道如何创建文件,但在这种情况下,它会覆盖所有数据:
import io
with open('text.txt', 'w', encoding='utf-8') as file:
file.write('text!')
Run Code Online (Sandbox Code Playgroud)
在*nix我可以做的事情:
#!/bin/sh
if [ -f text.txt ]
#If the file exists - append text
then echo 'text' >> text.txt;
#If the file doesn't exist - create it
else echo 'text' > text.txt;
fi;
Run Code Online (Sandbox Code Playgroud) 我只知道分割字符串和添加的两种简单方法 tuple
import re
1. tuple(map(lambda i: i, re.findall('[\d]{2}', '012345'))) # ('01', '23', '45')
2. tuple(i for i in re.findall('[\d]{2}', '012345')) # ('01', '23', '45')
Run Code Online (Sandbox Code Playgroud)
还有其他简单的方法吗?
请帮忙提出要求.
有两个表,artist和album.我想只选择那些专辑中包含图片的艺术家.也就是说,如果演员有10张专辑,其中只有一张有图片或不包含,我想跳过(只有所有专辑艺术家都有图片)
表艺术家:
artist_id
---------|
1 |
2 |
Run Code Online (Sandbox Code Playgroud)
表专辑:
artist_id | album_id | picture_id
---------------------------------
1 | 122... | true
1 | 123... | false
2 | 124... | true
2 | 125... | true
Run Code Online (Sandbox Code Playgroud)
所以,我想只选择艺术家在哪里artist_id=2(因为所有的专辑都有图片);
str = ''
for i in self.obj:
str += '[' + self.obj[i] + ']';
Run Code Online (Sandbox Code Playgroud)
有没有办法简化代码?