首页 > 解决方案 > 如何拆分和加入同时包含数字和字符串的文件?

问题描述

因此,对于以下变量,我要做的就是将 _ 替换为 ,:

这是我正在尝试的代码:

Thefile= '''
"Name"_"Course"_"Grade" 
"Norman White"_"Room 8-84, KMEC"_100
"Betty White"_"Room 8-85, KMEC"_98
"Student1"_"43 West Street, NYC"_95
"Student2"_"28 Mainstreet, Hoboken NJ"_93
"Student99"_"99 2nd. Ave., NYC"_85 '''

print(Thefile)
thefile_split = Thefile.split
[str(i) for i in thefile_split]
s = ","
s = s.join(thefile_split)
print(s)`

我收到以下错误:

TypeError:“builtin_function_or_method”对象不可迭代

我需要先格式化变量还是我的代码错误?

标签: pythonstringsplit

解决方案


由于您只需要用另一个字符替换一个字符,您可以简单地使用正则表达式来完成工作:

import re
Thefile= '''
"Name"_"Course"_"Grade" 
"Norman White"_"Room 8-84, KMEC"_100
"Betty White"_"Room 8-85, KMEC"_98
"Student1"_"43 West Street, NYC"_95
"Student2"_"28 Mainstreet, Hoboken NJ"_93
"Student99"_"99 2nd. Ave., NYC"_85 '''

result = re.sub('_', ',', Thefile)
print(result)

re.sub 在整个字符串中查找 '_' 并将其替换为 ','

输出

"Name","Course","Grade" 
"Norman White","Room 8-84, KMEC",100
"Betty White","Room 8-85, KMEC",98
"Student1","43 West Street, NYC",95
"Student2","28 Mainstreet, Hoboken NJ",93
"Student99","99 2nd. Ave., NYC",85 

推荐阅读