liwya 发表于 2017-4-24 09:59:07

python字符串2

这向下兼容简直反人类

>>> hello = u'Hello \u0020World'
>>> hello
'HelloWorld'
>>> mystr = "my string"
>>> mystr
'm'
>>> 'a'*3
'aaa'
def isStringLike(anobj):
try: anobj+''
except: return False
else:return True
print(isStringLike('1'))
print(isStringLike(2))


字符串去空格

>>> a = "ab "
>>> a
'ab '
>>> rstrip(a)
Traceback (most recent call last):
File "<pyshell#2>", line 1, in <module>
rstrip(a)
NameError: name 'rstrip' is not defined
>>> a.rstrip()
'ab'
>>> a
'ab '
>>> b = " a"
>>> b
' a'
>>> b.lstrip()
'a'
>>> c = " c "
>>> c
' c '
>>> c.strip
<built-in method strip of str object at 0x00000000035D67A0>
>>> c.strip()
'c'
>>>


切片

>>> t = 'abcdefg'
>>> t
''
>>> t
'defg'
>>> t
'defg'
>>> t[:]
'abcdefg'
>>> t[:-1]
'abcdef'
>>> t[:-2]
'abcde'
>>> t[::]
'abcdefg'
>>> t[::1]
'abcdefg'
>>> t[::-1]
'gfedcba'


使用切片反转

d = "a,b,c,d"
>>> d[::-1]
'd,c,b,a'
>>> d.split(",")[::-1]
['d', 'c', 'b', 'a']


判断字符串是否包含另一个字符串

d = "a,b,c,d"
>>> e = "a,"
>>> e in d
True
>>>
页: [1]
查看完整版本: python字符串2