将列表转换为字符串,然后将其返回列表 [Python]

发布于 2024-11-25 02:32:12 字数 669 浏览 0 评论 0原文

我遇到了一个问题,它是关于从列表转换为字符串来编辑它

我有这些名称的文件文本内容

Roby
Bucky
johan

然后我想在每个文件旁边添加 OK:1

所以我执行了这段代码

Names='a.txt' # here is the names
O=open(Names,'r') # we open the file content the names
iamList=O.readlines() # read the name it would be List !
imSting=str(iamList) # convert it to string
Edit=imSting.replace(r"\n","Ok:1") # Editing by adding
noname=Edit
noname=noname.split()
for PT in noname:
    PT.strip('[')
    print PT

并得到了这个结果 ['RobyOk:1', '巴基好的:1', '约翰'] 我想删除这些东西 [ , ' 我尝试了 stripreplace('[','')

有什么想法吗?

I got a problem, it's about converting from List to String to edit it

I have file text content these name

Roby
Bucky
johan

Then I want to add beside each one OK:1

so i do this code

Names='a.txt' # here is the names
O=open(Names,'r') # we open the file content the names
iamList=O.readlines() # read the name it would be List !
imSting=str(iamList) # convert it to string
Edit=imSting.replace(r"\n","Ok:1") # Editing by adding
noname=Edit
noname=noname.split()
for PT in noname:
    PT.strip('[')
    print PT

and i got this result
['RobyOk:1',
'BuckyOk:1',
'johan']

i want to delete these thing [ , '
i tried strip and replace('[','')

any ideas ?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

眼角的笑意。 2024-12-02 02:32:12

您无需将其转换为字符串即可在每个元素末尾添加 Ok:1

您可以使用 列表理解 来完成此操作,如下所示:

iamNewList = [e.rstrip() + 'Ok:1' for e in iamList]

或者,不太花哨,你可以这样做:

iamNewList = []
for e in iamList:
    iamNewList.append(e.rstrip() + 'Ok:1')

注意,rstrip< /a> 全部剥离字符串末尾的空白,例如换行符,我认为这就是您想要的。

You don't need to convert it to a string to add Ok:1 at the end of each element.

You could do it with a list comprehension like this:

iamNewList = [e.rstrip() + 'Ok:1' for e in iamList]

Alternatively, to be less fancy, you could do this:

iamNewList = []
for e in iamList:
    iamNewList.append(e.rstrip() + 'Ok:1')

Note, rstrip strips all whitespace, such as newlines, off of the end of the string, which I assume is what you want.

苍暮颜 2024-12-02 02:32:12

解决方案:

f = open('a.txt')
names = [line.strip() + 'Ok:1' for line in f.readlines()]
f.close()
for name in names:
    print(name)

我使用了'line.strip()',因为os.linesep(通常是'\n')可能与文件中使用的行分隔不同,使每一行仍然带有一个'\n'。

关于你的方法:
因为 iamList 是一个 List,所以由 str(iamList) 创建的该 List 的表示形式
已经包含括号“[”和逗号“,”:
这些是字符串表示的一部分。
print('imSting: ' + imSting) 将显示这一点。
因此,您可以直接从 imSting 中将 '\n' 替换为 'Ok:1' 并拆分
将新字符串放入列表中的 ', ' 部分:

(imSting.replace(r"\n", 'Ok:1')[2:-2] + 'Ok:1').split("' , '")

[2:-2] 仅返回 [' 和 '] 之间的字符,从而有效地删除括号。

第一个解决方案几乎可以是单行的,并且更容易阅读,因此更加“Pythonic”。
不过,养成阅读后关闭文件的习惯会更好。

solution:

f = open('a.txt')
names = [line.strip() + 'Ok:1' for line in f.readlines()]
f.close()
for name in names:
    print(name)

I used 'line.strip()', because the os.linesep (generally '\n') can be different than the line-seperation used in your file, leaving each line still with a '\n'.

About your approach:
Because iamList was a List, the representation of that List created by str(iamList)
already contained the brackets '[' and the commas ',':
these are part of the string representation.
print('imSting: ' + imSting) will show this.
So you could have replaced the '\n' by 'Ok:1' right from imSting and spliting the
new string into a list over the ', ' part:

(imSting.replace(r"\n", 'Ok:1')[2:-2] + 'Ok:1').split("', '")

The [2:-2] only returns the characters between [' and '] thus effectively removing the brackets.

The first solution could almost be a one-liner and is much easier to read, and therefore much more 'Pythonic'.
However, making a habit of closing the file after reading is better.

很酷又爱笑 2024-12-02 02:32:12

你的代码不起作用。最后一行末尾没有换行符,因此其中没有“Ok:1”。

试试这个:

[b.replace("\n","") + "Ok:1" for b in open("C:\\py\\a.txt","r")]

“扩展”版本:

newList = []
for b in open("C:\\py\\a.txt","r"):
  newList.append(b.replace("\n","") + "Ok:1")

Your code does not work. The last line has no line break at the end, so you don't have "Ok:1" in there.

Try this:

[b.replace("\n","") + "Ok:1" for b in open("C:\\py\\a.txt","r")]

"Expanded" version:

newList = []
for b in open("C:\\py\\a.txt","r"):
  newList.append(b.replace("\n","") + "Ok:1")
走走停停 2024-12-02 02:32:12

iamList = O.readlines() 将为您提供一个列表。

您不想将该列表转换为字符串。不惜一切代价避免字符串操作;这是不好的编码习惯。(因此,我也担心您向每个字符串添加 'Ok:1' 的原因。)

相反,只需执行 [ x+'好的!' for x in yourFile.read().splitlines()]

但是,您应该说明为什么要添加“Ok:1”,因为您可能会以错误的方式处理某些事情。 你应该说出你实际上想要做什么。

iamList = O.readlines() will give you a list.

You do NOT want to convert that list to a string. Avoid string manipulation at all costs; it's bad coding practice. (For this reason, I am also concerned about the reason you're adding 'Ok:1' to each string.)

Instead, just do [x+' OKAY!' for x in yourFile.read().splitlines()]

However you should say why you want to add "Ok:1", because it seems likely you're going about something the wrong way. You should say what you're actually trying to do.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文