Why am I getting unwanted newline in my string?

若如初见. 提交于 2021-02-09 10:56:35

问题


This should be so simple, it's silly. But I can't get it to work. I have a header which I define while reading a file:

    if "[gene=env]" in line or "[gene=HIV2gp7]" in line:
        header = line

now this header looks something like ">lcl|NC_001802.1_prot_NP_057856.1_8 [gene=env]" I need to attach a number to it like so: ">lcl|NC_001802.1_prot_NP_057856.1_8 [gene=env]1"

I have 100 identical headers, which have to be numbered 1 through 100 But whatever I try, I can't get the number on the same line. The output is always

>lcl|NC_001802.1_prot_NP_057856.1_8 [gene=env]
1
>lcl|NC_001802.1_prot_NP_057856.1_8 [gene=env]
2

etc.

I've tried:

number = 0
    for item in randoms[group_name]:
        number+=1
        headerx = str(header)+str(number)
        print(headerx)

and countless other things, but can't get it to work.


回答1:


I'm assuming you're getting your lines from a file using readline or readlines - if so, each line will end with a \n (newline) character. You need to strip those off:

line = line.rstrip('\n')


来源:https://stackoverflow.com/questions/42785776/why-am-i-getting-unwanted-newline-in-my-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!