打印字符并将其附加到单行python中

2024-09-16 06:16:52 发布

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

我在一个文件(inputfile.txt)中有许多字符串。每个字符串有99个字符。 现在我有了一个文件(position.txt),其中有一些数字。 我喜欢打印每个字符串的特定位置

输入文件:

BCCDDDCDCCDDDDDDABCDABCABDBACBDCAADDCBCABACBCCABCACBCCCCCBDBACABBBCBCBBCCACADAACCCBABADBCCAAABBCCBB
BCCDDDCDCDDDDCDDABCDABCABDBACBDCAADDCBCABACBCCABCACBCCCCCBDBADABBBCBCBACCACADAACCCBABADBCCAAABBCCBB
BCCDDDCDCDDDDCCDABCDABCABDBACBDCAADDABCABACBCCABCACBCCCCCBDBACABBBCBCBACCACADAACCCBABADBCCAAABBCCBB

我需要这样的输出文件:

DDDCBCABACBCCABCABCBBCCACADAACCC
CDDDCDCDDDDCDDABCDABCABACBDCAADC
CCDDDCDCDDDDCCDABCDABCABDBACBCCA

位置是随机数

位置文件:

10
11
16
20
24
30
32
33
34
36
43
46
47
48
50
53
54
58
60
62
63
64
69
71
73
74
76
77
82

我正在使用以下代码:

***seq=np.loadtxt('inputfile', dtype='str')
p = open( "osition.txt", "r" )
for line in p:
    l=int(line)
    ll=l-1
    print(seq[ll], end="")***

它在一行中打印输入,如下所示:

DDDCBCABACBCCABCABCBBCCACADAACCCCDDDCDCDDDDCDDABCDABCABACBDCAADCCCDDDCDCDDDDCCDABCDABCABDBACBCCA

我对python非常陌生。请帮助我获得所需的输出并将其保存在文本文件中。 多谢各位


Tags: 文件字符串txtlineposition数字seqll
2条回答

在上面的代码片段中,“inputfile”的内容被读取为字符串数组。根据您需要的注释——“打印每个字符串的特定位置”,您将需要添加另一个循环来迭代每个字符串并打印该字符串

建议代码:

seq=np.loadtxt('inputfile', dtype='str')
p = open( "position.txt", "r" )
for file_String in seq :   # Iterate over each string
    for line in p:
        l=int(line)
        ll=l-1
        print(file_String[ll], end="")
    print ("")     # Adding new line after each string.

要写入文件的优化代码:

import numpy as np
seq=np.loadtxt('inputfile.txt', dtype='str')
pos=np.loadtxt('position.txt', dtype='int')

with open( "output.txt", "w" ) as nf :
    for fileString in seq :   # Iterate over each string
        s = "".join (map(lambda x: fileString[x], p))  # Replace second for loop by map.
        nf.write(s + "\n")    # "\n" can be replaced by os.sep if using non-linux OS

end是print()函数的关键字参数,您可以阅读here

去掉print语句中的end = "",这是分隔符,并将其设置为''-empty string,这意味着在每个print语句之后,都会打印一个空字符串,因此当您下次在循环中开始打印时,打印将从相同的位置继续进行。
请注意,默认情况下,分隔符为\n,表示换行符。

所以 print(seq[l1])就是你想要的,就像现在一样{}

相关问题 更多 >