在浮点数之前插入逗号

2024-04-27 20:59:36 发布

您现在位置:Python中文网/ 问答频道 /正文

我是新来的。我有一个string如下所示:

a= "1.1 Introduction 1.2 Inverse of a Non-Singular 1.3 Elementary Transformations  1.4 Applications 1.5 Applications of Matrices"

我希望在String中的数字之前插入逗号。

我尝试过的代码:

a= "1.1 Introduction 1.2 Inverse of a Non-Singular 1.3 Elementary Transformations  1.4 Applications 1.5 Applications of Matrices"

b = ""
for i in a:
   print(i)
   try: 
       temp = int(i)
       b = b+ ","+ temp
   except:
       b = b + i

但这是错误的。请帮我解决一些问题

所需输出:

"1.1 Introduction, 1.2 Inverse of a Non-Singular, 1.3 Elementary Transformations,  1.4 Applications, 1.5 Applications of Matrices"

Tags: of代码string数字tempintroduction逗号non
1条回答
网友
1楼 · 发布于 2024-04-27 20:59:36

这可能会有帮助:

import re

a= "10.1 Introduction 10.2 Inverse of a Non-Singular 1.3 Elementary Transformations  1.4 Applications 1.5 Applications of Matrices"

re.sub(r"\s+(\d+\.\d+)", r", \1", a)

相关问题 更多 >