相关疑难解决方法(0)

为什么这个Ruby对象既有to_s又检查看起来做同样事情的方法?

为什么这个Ruby对象to_sinspect看起来做同样事情的方法?

p方法调用inspect并放置/打印to_s用于表示对象的调用.

如果我跑

class Graph
  def initialize
    @nodeArray = Array.new
    @wireArray = Array.new
  end
  def to_s # called with print / puts
    "Graph : #{@nodeArray.size}"
  end
  def inspect # called with p
    "G"
  end
end

if __FILE__ == $0
  gr = Graph.new
  p gr
  print gr
  puts gr
end
Run Code Online (Sandbox Code Playgroud)

我明白了

G
Graph : 0
Graph : 0
Run Code Online (Sandbox Code Playgroud)
  • 那么,为什么Ruby有两个函数做同样的事情呢?to_s和之间有什么区别inspect
  • 这有什么之间的区别puts,print以及p

如果我注释掉 …

ruby printing object

62
推荐指数
5
解决办法
4万
查看次数

什么是打印(f“...”)

我正在阅读一个 python 脚本,它接受 XML 文件的输入并输出一个 XML 文件。但是,我不明白打印语法。有人可以解释一下finprint(f"...")是做什么的吗?

args = parser.parser_args()

print(f"Input directory: {args.input_directory}")
print(f"Output directory: {args.output_directory}")
Run Code Online (Sandbox Code Playgroud)

python

48
推荐指数
3
解决办法
9万
查看次数

为什么反斜杠会出现两次?

当我创建一个包含反斜杠的字符串时,它们会重复:

>>> my_string = "why\does\it\happen?"
>>> my_string
'why\\does\\it\\happen?'
Run Code Online (Sandbox Code Playgroud)

为什么?

python string escaping repr backslash

46
推荐指数
2
解决办法
1万
查看次数

结合 f 字符串和原始字符串文字

我想知道如何在使用 f-string 的同时r获取原始字符串文字。我目前有它如下但想要允许任何名称替换的选项Alex我正在考虑添加一个 f 字符串,然后用Alex花括号替换并将用户名放在里面,但这不适用于r.

username = input('Enter name')
download_folder = r'C:\Users\Alex\Downloads'
Run Code Online (Sandbox Code Playgroud)

python python-3.x f-string

44
推荐指数
3
解决办法
2万
查看次数

Python艰难的方式 - 练习6 - %r与%s

http://learnpythonthehardway.org/book/ex6.html

Zed似乎在这里使用%r%s互换,两者之间有什么区别吗?为什么不一直使用%s

此外,我不知道在文档中搜索什么以查找更多信息.什么是%r%s究竟叫什么名字?格式化字符串?

python

41
推荐指数
2
解决办法
6万
查看次数

python 2.7.5中的str()vs repr()函数

python 2.7.5 str()repr()函数有什么区别?

python.org上的说明:

str()函数用于返回值相当于人类可读的值的表示,同时repr()用于生成可由解释器读取的表示(或者SyntaxError如果没有等效语法则强制执行)

但这对我来说并不清楚.

一些例子:

>>> s = 'Hello, world.'
>>> str(s)
'Hello, world.'
>>> repr(s)
"'Hello, world.'"      # repr is giving an extra double quotes
>>> str(1.0/7.0)
'0.142857142857'
>>> repr(1.0/7.0)
'0.14285714285714285'  # repr is giving value with more precision
Run Code Online (Sandbox Code Playgroud)

所以我想知道以下内容

  1. str()应该何时使用,何时使用repr()
  2. 在哪些情况下我可以使用它们中的任何一个?
  3. 什么可以str()做哪些repr()不可以?
  4. 什么可以repr()做哪些str()不可以?

python string repr python-2.7

28
推荐指数
1
解决办法
5万
查看次数

如何摆脱python windows文件路径字符串中的双反斜杠?

我有一本字典:

my_dictionary = {"058498":"table", "064165":"pen", "055123":"pencil"}
Run Code Online (Sandbox Code Playgroud)

我迭代它:

for item in my_dictionary:
    PDF = r'C:\Users\user\Desktop\File_%s.pdf' %item
    doIt(PDF)

def doIt(PDF):
    part = MIMEBase('application', "octet-stream")
    part.set_payload( open(PDF,"rb").read() )
Run Code Online (Sandbox Code Playgroud)

但我得到这个错误:

IOError: [Errno 2] No such file or directory: 'C:\\Users\\user\\Desktop\\File_055123.pdf'
Run Code Online (Sandbox Code Playgroud)

它无法找到我的文件.为什么它认为文件路径中有双反斜杠?

python dictionary file path

23
推荐指数
2
解决办法
6万
查看次数

Django 中的 __str__ 函数在做什么?

我正在阅读并试图理解 django 文档,所以我有一个合乎逻辑的问题。

有我的models.py文件

from django.db import models

# Create your models here.


class Blog(models.Model):
    name = models.CharField(max_length=255)
    tagline = models.TextField()

    def __str__(self):
        return self.name



class Author(models.Model):
    name = models.CharField(max_length=255)
    email = models.EmailField()

    def __str__(self):
        return self.name



class Post(models.Model):
    blog = models.ForeignKey(Blog)
    headline = models.CharField(max_length=255)
    body_text = models.TextField()
    pub_date = models.DateField()
    mod_date = models.DateField()
    authors = models.ManyToManyField(Author)
    n_comments = models.IntegerField()
    n_pingbacks = models.IntegerField()
    rating = models.IntegerField()

    def __str__(self):
        return self.headline
Run Code Online (Sandbox Code Playgroud)

__str__每个类中的每个函数在这里做什么?我需要这些功能的原因是什么?

python django django-models

20
推荐指数
3
解决办法
4万
查看次数

浮点数和字符串转换的奇怪行为

我把它键入python shell:

>>> 0.1*0.1
0.010000000000000002
Run Code Online (Sandbox Code Playgroud)

我预计0.1*0.1不是0.01,因为我知道基数10中的0.1在基数2中是周期性的.

>>> len(str(0.1*0.1))
4
Run Code Online (Sandbox Code Playgroud)

因为我看过20个字符,所以我预计会得到20分.我为什么得到4?

>>> str(0.1*0.1)
'0.01'
Run Code Online (Sandbox Code Playgroud)

好吧,这解释了为什么我len给了我4,但为什么要str回来'0.01'

>>> repr(0.1*0.1)
'0.010000000000000002'
Run Code Online (Sandbox Code Playgroud)

为什么str圆而repr不是?(我已经阅读了这个答案,但我想知道他们如何决定何时str轮流浮动而不是什么时候)

>>> str(0.01) == str(0.0100000000001)
False
>>> str(0.01) == str(0.01000000000001)
True
Run Code Online (Sandbox Code Playgroud)

所以它似乎是浮子准确性的问题.我以为Python会使用IEEE 754单精度浮点数.所以我这样检查过:

#include <stdint.h>
#include <stdio.h> // printf

union myUnion {
    uint32_t i; // unsigned integer 32-bit type (on every machine)
    float f;    // a type you want to play with
};

int main() {
    union myUnion testVar; …
Run Code Online (Sandbox Code Playgroud)

python floating-point python-2.x

18
推荐指数
2
解决办法
2639
查看次数

打印对象如何产生与str()和repr()不同的输出?

我在解释器上测试了一些代码,我注意到了这个sqlite3.Row类的一些意外行为.

我的理解是print obj总是得到相同的结果print str(obj),并且obj在解释器中输入将得到相同的结果print repr(obj),但是不是这样的情况sqlite3.Row:

>>> print row       # the row object prints like a tuple
(u'string',)
>>> print str(row)  # why wouldn't this match the output from above?
<sqlite3.Row object at 0xa19a450>

>>> row             # usually this would be the repr for an object
(u'string',)
>>> print repr(row) # but repr(row) is something different as well!
<sqlite3.Row object at 0xa19a450>
Run Code Online (Sandbox Code Playgroud)

我认为sqlite3.Row必须是它的子类tuple,但我仍然不明白幕后可能会导致这种行为的是什么.有谁能解释一下?

这是在Python 2.5.1上测试的,不确定其他Python版本的行为是否相同. …

python sqlite

17
推荐指数
1
解决办法
922
查看次数