如何在Python中去掉字符串末尾的逗号?

3 投票
5 回答
21879 浏览
提问于 2025-04-15 22:23

我该怎么去掉字符串末尾的逗号呢?我试过了

awk = subprocess.Popen([r"awk", "{print $10}"], stdin=subprocess.PIPE)
awk_stdin = awk.communicate(uptime_stdout)[0]
print awk_stdin
temp = awk_stdin
t = temp.strip(",")

还试过 t = temp.rstrip(","),但是都不管用。


这是代码:

uptime = subprocess.Popen([r"uptime"], stdout=subprocess.PIPE)
uptime_stdout = uptime.communicate()[0]
print uptime_stdout

awk = subprocess.Popen([r"awk", "{print $11}"], stdin=subprocess.PIPE)
awk_stdin = awk.communicate(uptime_stdout)[0]
print repr(awk_stdin)
temp = awk_stdin
tem = temp.rstrip("\n")
logfile = open('/usr/src/python/uptime.log', 'a')
logfile.write(tem + "\n")
logfile.close()

这是输出结果:

 17:07:32 up 27 days, 37 min,  2 users,  load average: 5.23, 5.09, 4.79

5.23,
None
Traceback (most recent call last):
  File "uptime.py", line 21, in ?
    tem = temp.rstrip("\n")
AttributeError: 'NoneType' object has no attribute 'rstrip'

5 个回答

2

去掉字符串末尾的所有逗号:

str = '1234,,,'
str = str.rstrip(',')
7

呃,怎么说呢,这个方法还是挺经典的:

if len(str) > 0:
    if str[-1:] == ",":
        str = str[:-1]

不过想想,rstrip 本身应该是可以正常工作的,所以你从 awk 得到的字符串可能和你预期的不太一样。我们需要看看这个字符串。


我怀疑是因为你的字符串实际上并没有以逗号结尾。当你运行:

str = "hello,"
print str.rstrip(",")

str = "hello,\n"
print str.rstrip(",")
print str.rstrip(",\n")

输出结果是:

hello
hello,

hello

换句话说,如果字符串的末尾有换行符和逗号,你需要用 rstrip 去掉这两个字符 ",\n"


好的,根据你的评论,看看你尝试的这个:

uptime = subprocess.Popen([r"uptime"], stdout=subprocess.PIPE)
uptime_stdout = uptime.communicate()[0]
print uptime_stdout
awk = subprocess.Popen([r"awk", "{print $11}"], stdin=subprocess.PIPE)
awk_stdin = awk.communicate(uptime_stdout)[0]
print repr(awk_stdin)
temp = awk_stdin
tem = temp.rstrip("\n")
logfile = open('/usr/src/python/uptime.log', 'a')
logfile.write(tem + "\n")
logfile.close()

你从两个 print 语句中实际得到了什么?还有,什么内容被添加到了日志文件里?

我这边的 uptime 并没有 $11

23:43:10 up  5:10,  0 users,  load average: 0.00, 0.00, 0.00

但你的可能会有所不同。

不过,我们还是需要看看你脚本的输出结果。

7

当你说

awk = subprocess.Popen([r"awk", "{print $11}"], stdin=subprocess.PIPE)
awk_stdout = awk.communicate(uptime_stdout)[0]

时,awk处理的结果会被打印到标准输出(比如终端)。这时候,awk_stdout被设置为None。当你尝试执行awk_stdout.rstrip('\n')时,会出现一个AttributeError错误,因为None这个东西没有叫rstrip的属性。

而当你说

awk = subprocess.Popen([r"awk", "{print $11}"], stdin=subprocess.PIPE,
                       stdout=subprocess.PIPE)
awk_stdout = awk.communicate(uptime_stdout)[0]

时,什么都不会被打印到标准输出(比如终端),这时候awk_stdout会得到awk命令的输出,内容会以字符串的形式存储。

撰写回答