【问题标题】:python removing ' ' in string? [duplicate]python删除字符串中的''? [复制]
【发布时间】:2016-01-16 08:03:56
【问题描述】:

我正在尝试从我的 Raspberry Pi B+ 上的 GPS 模块获取经度、纬度和高度。

目前在此处运行此代码:

## Prints the latitude and longitude every second.
import time
import microstacknode.hardware.gps.l80gps

if __name__ == '__main__':
    gps = microstacknode.hardware.gps.l80gps.L80GPS()
    while True:
        try:
            data = gps.get_gpgga()
        except microstacknode.hardware.gps.l80gps.NMEAPacketNotFoundError:
            continue
        List = [list(data.values())[x] for x in [7, 9, 12]]
        string=str(List)
        string = string[1:-1]
        text_file = open("/home/pi/fyp/gps.txt","a")
        text_file.write(string + "\n")
        time.sleep(1)

这是上述代码的输出:

0.0, 0.0, '10.2'
0.0, 0.0, '3.2'
0.0, 0.0, '10.1'
0.0, 0.0, '3.1'
0.0, 0.0, '4.5'
0.0, 0.0, '20.1'
0.0, 0.0, '3583.1232'
0.0, 0.0, '102.01'
0.0, 0.0, '32.131'
0.0, 0.0, '421.32'
0.0, 0.0, '12391.11'
0.0, 0.0, '323.411'

是否可以删除输出最后一部分中的 '' 引号,只保留输出前两部分中的数字?

【问题讨论】:

  • 简单地说:text_file.write(string.replace("'", '') + "\n").
  • 另外,你试过用谷歌搜索你的问题的标题吗?

标签: python string text text-files


【解决方案1】:

因为您要将列表转换为字符串,实际上您不应该这样做。我建议改用', '.join()

List = [list(data.values())[x] for x in [7, 9, 12]]
string = ', '.join(map(str, List))

让我们看看有什么问题:

>>> l = ['123', 456]
>>> str(l)
"['123', 456]"

>>> print(str(l))
['123', 456]

>>> ', '.join(map(str, l))
'123, 456'

>>> print(', '.join(map(str, l)))
123, 456

因为 Python 使用引号来表示:这个对象是一个字符串

当您转换其中包含字符串对象的对象时,引号将仍然存在而不是自动删除。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-05-06
    • 2021-07-04
    • 2021-06-05
    • 1970-01-01
    • 2017-02-15
    • 1970-01-01
    • 2010-10-26
    • 1970-01-01
    相关资源
    最近更新 更多