什么是Perl chomp函数的Python等价物,如果它是换行符,它会删除字符串的最后一个字符?
我试图从python中的字符串中删除最后3个字符,我不知道这些字符是什么,所以我无法使用rstrip,我还需要删除任何空格并转换为大写
一个例子是:
foo = "Bs12 3ab"
foo.replace(" ", "").rstrip(foo[-3:]).upper()
Run Code Online (Sandbox Code Playgroud)
这工作并给了我BS12这是我想要的,但是如果最后的第4和第3个字符是相同的,我放松了两个,例如,如果foo = "BS11 1AA"我得到'BS'
例子foo可能是:
BS1 1AB
bs11ab
BS111ab
Run Code Online (Sandbox Code Playgroud)
字符串可以是6或7个字符,我需要删除最后3个字符(假设没有空格)
有小费吗?
我有一堆字符串
他们中的一些人 ' rec'
我想删除它只有那些是最后4个字符
再说一句话
somestring='this is some string rec'
Run Code Online (Sandbox Code Playgroud)
我希望它是:
somestring='this is some string'
Run Code Online (Sandbox Code Playgroud)
什么是python方法来解决这个问题?
Python 2.6 (trunk:66714:66715M, Oct 1 2008, 18:36:04)
[GCC 4.0.1 (Apple Computer, Inc. build 5370)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> path = "/Volumes/Users"
>>> path.lstrip('/Volume')
's/Users'
>>> path.lstrip('/Volumes')
'Users'
>>>
Run Code Online (Sandbox Code Playgroud)
我期待输出path.lstrip('/Volumes')应该是/Users
我使用Python 3来处理文件名,这是我的代码:
name = 'movies.csv'
table_name = name.strip(".csv")
Run Code Online (Sandbox Code Playgroud)
table_name的期望值应该是"movies",而table_name仍然返回"movie".
它为什么这样做?
我试图理解python中的string.strip()正在做什么:
In [35]: t1 = '-MIN-North'
In [36]: t1.strip('-MIN-')
Out[36]: 'orth'
In [37]: t2 = '-MIN-north'
In [38]: t2.strip('-MIN-')
Out[38]: 'north'
Run Code Online (Sandbox Code Playgroud)
为什么t1.strip('-MIN-')不等于'North'但t2.strip('-MIN-')等于'north'?
Python中有一个非常有用的函数叫做strip().C++中有类似的吗?
我正在尝试使用删除后缀删除文件名的 .png 部分
'x.png'.removesuffix('.png')
但它不断返回:
AttributeError: 'str' object has no attribute 'removesuffix'
我试过其他一些字符串函数,但我一直得到“str”对象没有属性“”。我该怎么做才能解决这个问题?
我想知道rstrip和lstrip在python中是如何工作的.说,如果我有一个字符串
>> a = 'thisthat'
>> a.rstrip('hat')
out : 'this'
>> a.lstrip('this')
out: 'at'
>> a.rstrip('cat')
out: 'thisth'
Run Code Online (Sandbox Code Playgroud)
如何剥离一个单词?
理想情况下,输出应该是"thist"(对于第一种情况)和"那种"(对于第二种情况)对吗?
或者它是否像正则表达式一样,匹配每个字符,以及它最终剥离的哪个字符(第三种情况)?
注意:我不是在寻找替换我只是想知道从字符串中剥离子字符串时strip是如何工作的.