如何判断用户输入的字符串的编码格式

z752964360 2011-12-14 06:24:45
比如运行 一个接受参数的py程序 python a.py --keywd 谢谢
这个参数传入后是不是被py解释器装换#coding=utf-8 的格式?还是sys.getdefaultencoding的格式?
...全文
120 3 打赏 收藏 转发到动态 举报
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
zhang_zhiwei2 2013-03-13
  • 打赏
  • 举报
回复
/** * 判断字符串的编码 * * @param str * @return */ public static String getEncoding(String str) { String encode = "GB2312"; try { if (str.equals(new String(str.getBytes(encode), encode))) { String s = encode; return s; } } catch (Exception exception) { } encode = "ISO-8859-1"; try { if (str.equals(new String(str.getBytes(encode), encode))) { String s1 = encode; return s1; } } catch (Exception exception1) { } encode = "UTF-8"; try { if (str.equals(new String(str.getBytes(encode), encode))) { String s2 = encode; return s2; } } catch (Exception exception2) { } encode = "GBK"; try { if (str.equals(new String(str.getBytes(encode), encode))) { String s3 = encode; return s3; } } catch (Exception exception3) { } return ""; }
z752964360 2011-12-14
  • 打赏
  • 举报
回复
万分感谢!
iambic 2011-12-14
  • 打赏
  • 举报
回复
一般是sys.getfilesystemencoding()。因为实际的参数是操作系统传进去的,和python本身的编码系统无关。

37,721

社区成员

发帖
与我相关
我的任务
社区描述
JavaScript,VBScript,AngleScript,ActionScript,Shell,Perl,Ruby,Lua,Tcl,Scala,MaxScript 等脚本语言交流。
社区管理员
  • 脚本语言(Perl/Python)社区
  • IT.BOB
加入社区
  • 近7日
  • 近30日
  • 至今

试试用AI创作助手写篇文章吧