简体   繁体   English

如何使用python从列中的所有数据中删除最后一个字符?

[英]How to remove the last character from all the data in a column using python?

I have data like this in a column of a table.我在表格的一列中有这样的数据。

RcHm_v2.0_CPg0501681
RcHm_v2.0_CPg0501691
RcHm_v2.0_CPg0501701
RcHm_v2.0_CPg0501711
RcHm_v2.0_CPg0501721
RcHm_v2.0_CPg0501731

I need to remove the last character from all these data.我需要从所有这些数据中删除最后一个字符。 I have this,我有这个,

for row in reader:
    transcript_id = row[1]
    gene_id = transcript_id.split(".")[0]
    row[1] = gene_id
    row[2] = gene_id
    row[16] = transcript_id
    writer.writerow(row)

From the 2nd line,从第 2 行开始,

    gene_id = transcript_id.split(".")[0]

it will remove all the things after the "."(dot).(Just consider the above line of code).它将删除“。”(点)之后的所有内容。(只需考虑上面的代码行)。 I need to remove the last character.我需要删除最后一个字符。 I'll be grateful if someone can help me.如果有人可以帮助我,我将不胜感激。

Thank you.谢谢你。

那么gene_id = transcript_id[:-1] ,这是一个简单的字符串切片,请阅读这篇文章

gene_id = gene_id[:-1]基因 ID = 基因 ID[:-1]

This will return all but the last character and reassign it to the same variable这将返回除最后一个字符之外的所有字符并将其重新分配给同一个变量

If you only need to remove the last character, why are you using split?如果您只需要删除最后一个字符,为什么要使用拆分?

gene_id = transcript_id[0:len(transcript_id)-1]

Here is a simple example这是一个简单的例子

var1 = "Something.Else"
var2 = var2=var1[0:len(var1)-1]
print(var2)
Something.Els

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM