Python中的%a也能占位?

img


Python里的%a也是占位符吗,给什么占位,我查了网上也没搜到相关问题的询问和回答

参见官方文档:https://docs.python.org/zh-cn/3/library/stdtypes.html#index-36
%a 会调用 ascii 函数转换任何 Python 对象。

  • 给你找了一篇非常好的博客,你可以看看是否有帮助,链接:python的占位符——%
  • 除此之外, 这篇博客: Python——占位的几种运用形式中的 %号占位符 部分也许能够解决你的问题, 你可以仔细阅读以下内容或跳转源博客中阅读:
  • %[ 转换标记 ][ 宽度 [ .精确度] ] 转换类型

    转换标记解释样例
    -左对齐(默认右对齐)print “the number is %-9f” % 1991
    +在正数后加上+print “the number is %+9f or %+0.9f” % (1991,-1991)
    (a space)正数之前保留空格print “the number is % 0.1f” % 1991
    #显示进制标识print “the number is %#x” % 1991
    0位数不够0来凑print “the number is %010.2f” % 1991
    • %s 采用str方式字符串输出
    # 普通占位
    print "hello %s" % "world" 
    # 多值占位
    print "hello %s,i'm %s" % ("world", "python")
    # 指定占位长度
    print "I‘m %s, I was born in %6s" % ('python',1991)
    # I‘m python, I was born in   1991    1991占6位右对齐  相当于字符串的rjust方法
    print "I‘m %s, I was born in %-6s" % ('python',1991)
    # I‘m python, I was born in 1991    1991占6位左对齐  相当于字符串的ljust方法
    # 字符串居中可以使用字符串的center方法
    # 键值对占位
    print "I‘m %(name)s, I was born in %(born)s" % {'name':'python','born':'1991'}
    
    • %r 采用repr方式显示
    # 简单来说str更人性化,repr更精确。str旨在可读性上(对人),repr旨在标准上(对机器)。
    print "%r" %"\n你好\n" 
    '\n\xe4\xbd\xa0\xe5\xa5\xbd\n'
    print "%s" %"\n你好\n" 
    
    你好
    
    
  • 以下回答由chatgpt基于相关博客总结生成:

    %a并不是Python中的一个占位符,正确的占位符应该是%s。%s是格式化字符串中最常用的占位符,用法示例如下:

    string = "hello" print("this is a string: %s" % string)

    输出:this is a string: hello

    %s占位符会被字符串string替代。

    另外,%格式化字符串中有很多其他的占位符,具体可以看参考资料中的段落2。其中要注意,使用%进行格式化字符串时,如果要输出%符号,应该使用%%表示一个百分号。例如:

    percent = 0.23 print("percent: %.2f%%" % (percent*100))

    输出:percent: 23.00%