简体   繁体   English

如何从 Python 中的混合字符串中删除单个字符

[英]How to Remove single character from a Mixed string In Python

桌子

I have one table (Please Ref Image) In this Table I want to remove "A" char from each Row How can I do in Python.我有一张表(请参考图片)在这个表中我想从每一行中删除“A”字符我如何在 Python 中做。

Below is my code using regexe_replace but code is not optimised I want optimised code下面是我使用regexe_replace代码,但代码没有优化 我想要优化的代码

 def re(s):
      return regexp_replace(s, "A", "").cast("Integer")

    finalDF = finalD.select(re(col("C0")).alias("C0"),col("C1"),
                        re(col("C2")).alias("C2"),
                        re(col("C3")).alias("C3"),col("C4"),
                        re(col("C5")).alias("C5"),
                        re(col("C6")).alias("C6"),col("C7"),
                        re(col("C8")).alias("C8"),
                        re(col("C9")).alias("C9"),col("C10"),
                        re(col("C11")).alias("C11"),col("C12"),
                        re(col("C13")).alias("C13"),
                        re(col("C14")).alias("C14"),col("C15"),
                        re(col("C16")).alias("16"),col("C17"),
                        re(col("C18")).alias("18"),
                        re(col("C19")).alias("C19"),col("Label"))
    finalDF.show(2)

Thank you in Advance.先感谢您。

Why regex?为什么是正则表达式? Regex will be over kill.正则表达式将结束。

If you have data in format you have given, then use replace function as below:如果您有给定格式的数据,请使用如下替换功能

Content of master.csv: master.csv 的内容:

A11| 6|A34|A43|
A11| 6|A35|A44|

Code :代码 :

with open('master.csv','r') as fh:
    for line in fh.readlines():
        print "Before - ",line
        line = line.replace('A','')
        print "After - ", line
        print "---------------------------"

Output:输出:

C:\Users\dinesh_pundkar\Desktop>python c.py
Before -  A11| 6|A34|A43|
After -  11| 6|34|43|
---------------------------
Before -  A11| 6|A35|A44|
After -  11| 6|35|44|
---------------------------

Code with replacing 'A' from complete data in in one shot (without going line by line)一次性从完整数据中替换“A”的代码(无需逐行)

with open("master.csv",'r') as fh:
    data = fh.read()
    data_after_remove = data.replace('A','')
    print "Before remove ..."
    print data
    print "After remove ..."
    print data_after_remove

Output:输出:

C:\Users\dinesh_pundkar\Desktop>python c.py
Before remove...
A11| 6|A34|A43|
A11| 6|A35|A44|
After remove ...
11| 6|34|43|
11| 6|35|44|

C:\Users\dinesh_pundkar\Desktop>

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

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