【python中检查字符串是否由字母组成的方法:string.isalpha()】教程文章相关的互联网学习教程文章

python – 替换string中第n个子串的出现【代码】

我想替换字符串中第n个子串的出现. 必须有一些与我想做的事情相同的东西 mystring.replace(“substring”,2nd) 实现这一目标的最简单,最恐怖的方法是什么? 为什么不重复:我不想使用正则表达式这种方法,我发现的类似问题的大多数答案只是正则表达式剥离或真正复杂的功能.我真的希望尽可能简单而不是正则表达式解决方案.解决方法:您可以使用带有str.find的while循环来查找第n个匹配项(如果它存在)并使用该位置创建新字符串:def nt...

在Python类继承中继承docstrings【代码】

我正在尝试在Python中进行一些类继承.我希望每个班级和继承的班级都有良好的文档字符串.所以我认为对于继承的类,我希望它: >继承基类docstring>可能会将相关的额外文档附加到docstring 在类继承情况下是否有任何(可能是优雅或pythonic)方式进行此类文档字符串操作?多重继承怎么样?解决方法:你并不是唯一的一个!不久之前有关于comp.lang.python的讨论,并且创建了一个食谱.看看here.""" doc_inherit decoratorUsage:class Foo(ob...

为什么python string split()没有拆分【代码】

我有以下python代码.class MainPage(BaseHandler):def post(self, location_id):reservations = self.request.get_all('reservations')for r in reservations:a=str(r)logging.info("r: %s " % r)logging.info("lenr: %s " % len(r))logging.info("a: %s " % a)logging.info("lena: %s " % len(a))r.split(' ')a.split(' ')logging.info("split r: %s " % r)logging.info("split a: %s " % a)我得到以下日志打印输出.INFO 2012...

在String Python中计算元音【代码】

我正在尝试计算字符串中特定字符的出现次数,但输出错误. 这是我的代码:inputString = str(input("Please type a sentence: ")) a = "a" A = "A" e = "e" E = "E" i = "i" I = "I" o = "o" O = "O" u = "u" U = "U" acount = 0 ecount = 0 icount = 0 ocount = 0 ucount = 0if A or a in stri :acount = acount + 1if E or e in stri :ecount = ecount + 1if I or i in stri :icount = icount + 1if o or O in stri :ocount = ocou...

从Python中的String中提取Number【代码】

我是Python的新手,我有一个String,我想从字符串中提取数字.例如:str1 = "3158 reviews" print (re.findall('\d+', str1 ))输出为[‘4′,’3’] 我想只获得3158,最好是整数,而不是List.解决方法:您可以使用str.isdigit方法按数字过滤字符串,>>> int(filter(str.isdigit, str1)) 3158

python – 根据涉及len(string)给出KeyError的条件表达式从pandas DataFrame中删除行【代码】

我有一个pandas DataFrame,我想从中删除行,其中特定列中字符串的长度大于2. 我希望能够做到这一点(每this answer):df[(len(df['column name']) < 2)]但我得到错误:KeyError: u'no item named False'我究竟做错了什么? (注意:我知道我可以使用df.dropna()来删除包含任何NaN的行,但是我没有看到如何根据条件表达式删除行.)解决方法:当你执行len(df [‘column name’])时,你只得到一个数字,即DataFrame中的行数(即列本身的长度).如...

Python3中的StringIO【代码】

我使用的是Python 3.2.1,我无法导入StringIO模块.我用io.StringIO它可以工作,但我不能像numpy的genfromtxt这样使用它:x="1 3\n 4.5 8" numpy.genfromtxt(io.StringIO(x))我收到以下错误:TypeError: Can't convert 'bytes' object to str implicitly 当我写入导入StringIO时,它说ImportError: No module named 'StringIO'解决方法:when i write import StringIO it says there is no such module.从What’s New In Pytho...

在Python 3中替换_PyString_Resize【代码】

我正在移植一个使用C将Python的功能从2.x扩展到3的模块,并且在文档中找不到有关如何调整字符串大小的任何引用,只能找到如何获取其大小: http://docs.python.org/py3k/c-api/unicode.html?highlight=pyunicode#PyUnicode_GetSize 我如何转换此代码:_PyString_Resize(&buffer, (int)res);到python 3可以理解的一个?解决方法:虽然在链接的页面中没有记录,但unicodeobject.c确实包含两者int _PyUnicode_Resize(PyUnicodeObject **un...

为python安装stringtemplate3【代码】

我试图运行Python / cminus示例.从http://pypi.python.org/pypi/stringtemplate3/3.1开始,我使用sudo python setup.py install为python安装了stringtemplate3. 当我运行以此代码开头的cminus.py时.import sys import antlr3 import stringtemplate3我有错误.Traceback (most recent call last):File "cminus.py", line 3, in <module>import stringtemplate3File "/Library/Python/2.7/site-packages/stringtemplate3/__init__.py"...

Python,Google App Engine错误:断言类型(数据)是StringType,“write()参数必须是字符串”【代码】

我现在正在学习Google App Engine,其中有一本书是“使用Charles Severance的Google App Engine”. 我在第6章,到目前为止,我已经在templates文件夹中创建了app.yaml,index.py,index.html,在静态文件夹中创建了CSS文件. 我的index.py看起来像这样:import os import wsgiref.appengine.ext import webapp from google.appengine.ext import webapp from google.appengine.ext.webapp import templateclass MainHandler(webapp.Reques...

在python3中正确替换QString().arg方法【代码】

说到国际化 – 使用python2和PyQt4 – 格式化翻译字符串的“建议方法”是使用QString.arg()方法:from PyQt4.QtGui import QDialog #somewhere in a QDialog:self.tr("string %1 %2").arg(arg1).arg(arg2)但是python3-PyQt4中不存在QString(). 所以我的问题是,在python3中格式化任何翻译字符串的最佳方法是什么?我应该使用标准的python方法str.format()还是有更合适的东西?解决方法:QString :: arg方法实际上是C的有限字符串格式...

python – 如何在调用PyRun_String(…)后返回NULL时获取异常信息?【代码】

我试图运行以下代码:Py_Initialize(); PyObject *py_main = PyImport_AddModule("__main__"); PyObject *py_dict = PyModule_GetDict(py_main); PyObject *ret = PyRun_String(SOME_PYTHON_CODE, Py_file_input, py_dict, py_dict);但是在我生成的python代码(SOME_PYTHON_CODE)中似乎存在错误,因此ret出现为NULL,表示引发了异常.我怎样才能访问此例外?解决方法:你可以做:PyErr_Print();在标准错误上打印出标准堆栈跟踪.还有其他...

python – string.format(),其中{}在字符串内作为字符串【代码】

参见英文答案 > How can I print literal curly-brace characters in python string and also use .format on it? 10个请注意,您有一个类似于以下字符串的字符串’This string is {{}}’,并且您想将其转换为以下’此字符串是{wonderful}’ 如果你这样做’这个字符串是{{}}’.format(‘wonderful’)它将不起作用.实现这一目标的最佳方法是什么?解决方法:你只需要再多一对{}'This string is {{{...

Python给出“模块”对象没有属性’message_from_string’错误【代码】

我正在从C#转向Python,我猜我正在踩着一些名字问题,但我找不到问题.这是给我错误的当前类(第41行)import imaplib import os import emailclass EmailWrapper:hostname = None # herp username = None # derp password = None # might encrypt this if there is timedef __init__(self, host, user, passwd):self.hostname = hostself.username = user self.password = passwd# Create connection and return it def co...

在python中,为什么string.count()比循环更快?【代码】

在leetcode中,我有一个问题要检查一串无序的字符串“U”,“D”,“L”,“R”是否会形成一个圆圈. 我的意见如下:def judgeCircle(moves):l=r=u=d=0for i in moves:if i == 'L':l+=1if i == 'D':d+=1if i == 'R':r+=1if i == 'U':u+=1return ((l-r)==0) and ((u-d)==0)并且裁判认为它花费了239ms而另一个单线解决方案:def judgeCircle(moves):return (moves.count('R')==moves.count('L')) and (moves.count('U')==moves.count('D')...