小编tom*_*mas的帖子

如何用字符串连接`Object`?

如何连接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')))

python casting

11
推荐指数
2
解决办法
1万
查看次数

在Python中将文本附加到文件

  1. 如何检查文件是否存在?
  2. 如何将文本附加到文件?

我知道如何创建文件,但在这种情况下,它会覆盖所有数据:

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)

python io

7
推荐指数
1
解决办法
3万
查看次数

拆分一个字符串并添加到`tuple`中

我只知道分割字符串和添加的两种简单方法 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)

还有其他简单的方法吗?

python

4
推荐指数
1
解决办法
1846
查看次数

过滤两个表中的数据

请帮忙提出要求.

有两个表,artistalbum.我想只选择那些专辑中包含图片的艺术家.也就是说,如果演员有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(因为所有的专辑都有图片);

mysql sql left-join

2
推荐指数
1
解决办法
773
查看次数

简化迭代

str = ''

for i in self.obj:
    str += '[' + self.obj[i] + ']';
Run Code Online (Sandbox Code Playgroud)

有没有办法简化代码?

python iterator

0
推荐指数
1
解决办法
91
查看次数

标签 统计

python ×4

casting ×1

io ×1

iterator ×1

left-join ×1

mysql ×1

sql ×1