python - 如何拆分和加入同时包含数字和字符串的文件?
问题描述
因此,对于以下变量,我要做的就是将 _ 替换为 ,:
这是我正在尝试的代码:
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”对象不可迭代
我需要先格式化变量还是我的代码错误?
解决方案
由于您只需要用另一个字符替换一个字符,您可以简单地使用正则表达式来完成工作:
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
推荐阅读
- c - 如何阻止数组在c中被覆盖?
- javascript - 单击按钮后如何在文本输入字段中显示我写的内容?
- distinct - Impala 中的多个不同计数
- java - 如何在 java 中以 dd-mmm-yyyy 格式打印日期?
- python - 如何正确引用 Multiprocessing Pool.map 中的类的实例?
- java - WRONGTYPE 对持有错误值的键的操作
- azure - 无法加载文件或程序集“Microsoft.Azure.KeyVault,版本=3.0.0.0,文化=中性,PublicKeyToken=31bf3856ad364e35
- javascript - 将文件从浏览器拖到需要权限的桌面
- postgresql - PostgreSQL 交叉表:月行和日列;错误 rowid 数据类型不匹配 返回 rowid 数据类型
- python - 以最短的、人类可读的方式检查列表中的两个数字,而无需通过列表两次