简体   繁体   English

在python中使用strip()或rstrip()删除字符串末尾的空格

[英]Remove space at the end of a string using strip() or rstrip() in python

My goal is to read a csv file and then print the 10 items with One Single Space between them. 我的目标是读取一个csv文件,然后打印10个项目,它们之间只有一个空格。 Following are the tasks to do that: 以下是要执行的任务:

  1. If the string has more than one word than add "Double quotes" around it. 如果字符串中有多个单词,请在字符串前后加上“双引号”。

The problem i am facing is that if it is a single string but with white space at the end, i am supposed to remove it. 我面临的问题是,如果它是单个字符串,但末尾有空格,我应该将其删除。

I tried strip and rstrip in python, but it doesnt seem to work. 我在python中尝试了strip和rstrip,但似乎没有用。

Following is the code for it: 以下是它的代码:

with open(accidents_csv, mode='r', encoding="utf-8") as csv_file:
    csv_reader = csv.reader(csv_file, delimiter=",")
    count = 0
    for row in csv_reader:
        if count <=10:
            new_row = [beautify_columns(item) for item in row]
            print(' '.join(new_row))
            count +=1
def beautify_columns(col):
    col.strip()
    if(' ' in col):
        col = f'"{col}"'
    return col

The following image shows the current behavior of the code without removing the trailing spaces. 下图显示了代码的当前行为,未删除尾随空格。 该图显示了代码的当前行为,没有删除尾随空格。

Kindly advise me how to remove spaces at the end of a string 请告诉我如何删除字符串末尾的空格

You have to assign the result of strip(), ie 您必须分配strip()的结果,即

col = col.strip()

Only other thing to note is that strip() will remove whitespace (ie not just space characters) at beginning as well as end of the string. 唯一需要注意的是, strip()会在字符串的开头和结尾删除空格(即不仅是空格字符)。

Partially unrelated, but a csv.writer could natively meet your other requirements, because it will automatically quote fields containing a separator: 部分不相关,但是一个csv.writer本身可以满足您的其他要求,因为它会自动引用包含分隔符的字段:

with open(accidents_csv, mode='r', encoding="utf-8") as csv_file:
    csv_reader = csv.reader(csv_file, delimiter=",")
    csv_writer = csv.writer(sys.stdout, delimiter=" ")
    for count, row in enumerate(csv_reader):
        new_row = [item.strip() for item in row]
        csv_writer.writerow(new_row)
        if count >= 9: break

As said by @barny, strip() will remove all whitespace characters, including "\\r" or "\\t" . 正如@barny所说, strip()将删除所有空格字符,包括"\\r""\\t" Use strip(' ') if you want to only remove space characters. 如果只想删除空格字符,请使用strip(' ')

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

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