小编ako*_*ozi的帖子

格式化时可以将字符串转换为大写吗

动机

假设您有一个字符串在一个字符串中使用了两次。然而,在一种情况下它是较高的,而另一种情况是较低的。如果使用字典,解决方案似乎是添加一个大写的新元素。


假设我有一个 python 字符串准备格式化为:

string = "{a}_{b}_{c}_{a}"
Run Code Online (Sandbox Code Playgroud)

期望的输出为:

HELLO_by_hi_hello

我还准备了一本字典:

dictionary = {a: "hello", b: "bye", c: "hi"}
Run Code Online (Sandbox Code Playgroud)

无需与字典交互即可设置新元素,d例如"HELLO"

dictionary['d'] = dictionary['a'].upper()
string = "{d}_{b}_{c}_{a}"
string.format(**dictionary)
print(string)
>>> HELLO_bye_hi_hello
Run Code Online (Sandbox Code Playgroud)

有没有一种方法可以将元素设置a为在字符串的一种情况下始终为大写?例如:

string= "{a:upper}_{b}_{c}_{a}"
string.format(**dictionary)
print(string)
>>> HELLO_bye_hi_hello
Run Code Online (Sandbox Code Playgroud)

python string string-formatting python-2.x

5
推荐指数
2
解决办法
5913
查看次数

Pandas DataFrame根据列,索引值比较更改值

假设您有一个熊猫DataFrame,它在身体中有某种数据,而在和名称中有数字.columnindex

>>> data=np.array([['a', 'b', 'c'], ['d', 'e', 'f'], ['g', 'h', 'i']])
>>> columns = [2, 4, 8]
>>> index = [10, 4, 2]
>>> df = pd.DataFrame(data, columns=columns, index=index)
>>> df
    2  4  8
10  a  b  c
4   d  e  f
2   g  h  i
Run Code Online (Sandbox Code Playgroud)

现在假设我们想要在比较索引和列的基础上以某种方式操作数据帧.考虑以下.

其中index大于列替换字母'k':

    2  4  8
10  k  k  k
4   k  e  f
2   g  h  i
Run Code Online (Sandbox Code Playgroud)

其中index等于列替换字母为'U':

    2  4  8
10  k  k  k
4   k  U …
Run Code Online (Sandbox Code Playgroud)

python dataframe pandas

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

为什么在python中记录自定义错误以root身份显示?

编辑::root:出现的原因是因为我输入logging.error(...)而不是logger.error. 这导致程序默认为处理程序根。这更改了包括处理程序名称的一般格式。更正记录器并将错误名称添加到消息似乎可以创建正确的输出。

旧文本

使用日志记录包,我正在尝试记录自定义错误。这样做时会显示错误消息,但自定义错误异常似乎显示为 root。例如,一个简单的案例如下所示运行python 3.6.6

输入看起来像:

 import logging
 import logging.config

 logger = logging.getLogger(__name__)
 logger.setLevel(logging.INFO)
 HANDLER = logging.FileHandler('test.txt')
 logger.addHandler(HANDLER)
 FORMATTER = logging.Formatter('%(name)s - %(levelname)s - %(message)s')
 HANDLER.setFormatter(FORMATTER)

 class FailedToDoSimpleTaskError(Exception):
     pass

 def fail_todo_thing():
     raise FailedToDoSimpleTaskError('It was a good attempt though')

 try:
     fail_todo_thing()
 except FailedToDoSimpleTaskError as err:
     logging.error(err)
Run Code Online (Sandbox Code Playgroud)

输出看起来像:

__main__-ERROR:root:It was a good attempt though
Run Code Online (Sandbox Code Playgroud)

我想了解的是为什么它显示为 :root:,如果有任何方法可以使用 :FailedToDoSimpleTaskError: 显示它?

python error-handling logging

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

如何在python 3中将字符串转换为字典

从字符串开始:

S='a=65 b=66 c=67'
Run Code Online (Sandbox Code Playgroud)

你会如何创建一个类似于dict的输出 {'a':'65','b':'66','c':'67'}

尝试:

S='a=65 b=66 c=67'
L=s.split(' ')
D=dict()
A=''
i=0
While i<Len(L):
    A=L[i].split('=')
    D[a[i]]=a[i+1]
    i+2

print (D)
Run Code Online (Sandbox Code Playgroud)

第8行indexerror列表索引超出范围时出错

python dictionary python-3.x

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