繁体   English   中英

将Python代码转换为等效的C#

[英]Translate Python code to C# equivalent

我想将本书中的python代码示例重写为C#等效版本,以测试其功能。

代码如下:

q = "select target_id from connection where source_id=me() and target_type='user'"
my_friends = [str(t['target_id']) for t in fql.query(q)]

q = "select uid1, uid2 from friends where uid1 in (%s) and iud2 in (%s)" %
    (",".join(my_friends), ",".join(my_friends),)
mutual_friendships = fql(q)

我不知道符号%s是什么,代码中的(%s)是什么意思。 如果有人可以用C#编写等效的代码,我将不胜感激。

Python中的字符串格式化操作

%s将替换为%运算符之后传递的元组中的相应值。

它在Python中的工作方式

例如:

my_friends = [0, 2, 666, 123132]
print "select uid1 from friends where uid1 in (%s)" % (",".join(my_friends))

将打印此:

从朋友中选择uid1其中(0,2,666,123132)中的uid1

如何用C#替换

您需要使用String.Format() ,例如提到的。 此处: http//blog.stevex.net/string-formatting-in-csharp/

string formatString = "select uid1, uid2 from friends where uid1 in ({0}) and iud2 in ({1})"
string q = String.Format(formatString, yourReplacement1, yourReplacement2)

它的工作方式与Python的string format()方法非常相似(自python 2.6起可用)。

%s是字符串格式的替换占位符,在调用String.Format()或.NET中的类似函数时,其等效于{0}...{1}等。

string.Format

string.Format("select uid1, uid2 from friends where uid1 in ({0}) and iud2 in ({1})",
              <value for {0}>, 
              <value for {1}>);

对于任何字符串值, %s都将转换为{0}...{N} %d等也将全部用{0}...{N}语法表示,但是MSDN上定义了几种不同的格式字符串。 例如,有数字格式字符串日期格式字符串

暂无
暂无

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

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