小编ael*_*ath的帖子

Python 在特定子字符串之前提取十进制数

我想在特定子字符串之前提取一个数字(“百分比”)

我尝试使用拆分功能

str1="The percentage of success for Team A is around 7.5 per cent. What about their season ?"
print(str1.split("per cent",1)[0])
Run Code Online (Sandbox Code Playgroud)

预期结果: "7.5"

实际结果: "The percentage of success for Team A is around 7.5"

python regex string list-comprehension

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

如果项目不以“。”结尾,则连接列表项目。

我有一个字符串列表,如果它们的结尾不是“。”,我想将它们串联起来。

my_list=["This is my first string.","This is my second string, ","this is the middle of my second string","and this is the end of my second string."]
for index in range(len(my_list)):
    text=my_list[index]:
        if not text.endswith("."):
Run Code Online (Sandbox Code Playgroud)

预期 ["This is my first string.","This is my second string, this is the middle of my second string and this is the end of my second string"]

python

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

提取字符串中的子字符串

我有一个具有相同模式的字符串列表,我想提取这些字符串的中间

my_list=["This is my first string","This is my second string"]
my_list2=[string[5:] for string in my_list]
my_list2=[string[:-7] for string in my_list]
Run Code Online (Sandbox Code Playgroud)

输出:["is my first","is my second"] 我的解决方案正在工作,但是如何将两个列表理解简化为一行代码?

python

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

反转列表项值

我想反转列表中的所有值。我的列表由 0、1、2 和 3 组成(例如 [0,2,2,3,1,3,2]),我想反转项目的值(将所有 0 更改为 3,所有1 到,所有 2 到 1,所有 3 到 0 => [3,1,1,0,2,0,1])。

在 python 中可能吗?

我尝试使用列表理解但没有成功。

li=[0,2,2,3,1,3,2]
print(list(reversed(li)))
Run Code Online (Sandbox Code Playgroud)

我拥有的:[0,2,2,3,1,3,2] 我想要的:[3,1,1,0,2,0,1]

python

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

标签 统计

python ×4

list-comprehension ×1

regex ×1

string ×1