全部版块 我的主页
论坛 数据科学与人工智能 数据分析与数据科学 python论坛
1330 1
2015-05-04
Python strings come with a powerful set of processing tools. Python has no distinct type for individual characters; instead you just
use one-character strings.

Strings are derived from sequences, and are immutable. It is easy enough to digest with examples:

S = ''   # empty string with single quotes
S ="spam's"  # double quotes
S ='s\n\p\ta\x00m'  # escape
S=""" ...multipline .."""  # triple-quoted block strings
S=r'\tmp\spam' # Raw strings (no escapes"
S=b'sp\xc4m'  # byte strings
S=u'sp\u00c5m'  # Unicode
S1+S2 # concatenation
S*3  
S[i]
S[i:j]
len(S)
"a %s parrot" % kind   # string formatting expression
S.find('pa')
S.rstrip()  # remove whitespace
S.replace('pa','xx')
S.split(',')
S.isdigit()
S.lower()
S.endswith('spam')
'spam'.jjoin(strlist)  # delimiter join
for x in S: print(x)  # iteration
'spam' in S
[c*2 for c in S]
map(ord, S)
re.match('sp(.*)am', line)  # pattern matching: library module

二维码

扫码加我 拉你入群

请注明:姓名-公司-职位

以便审核进群资格,未注明则拒绝

全部回复
2015-5-4 23:38:50
notes:

index starts with 0, negative offset is added to the length of the string to derive a positive offset.

slicing s[:3] fetches items at offset 0 up to but not including 3

X[1:10:2] fetches every other item in X from offsets 1-9 with stride 2; it will collect items at offsets 1,3,5,7 and 9

strings can be converted between numeric types: int(S), float(S), str(1.234), str(1), repr(42), bin(13)

ord('s') can convert character to ASCII value, chr('115) is the reverse operation

s[0]='x' $ raises an error!

you need the following to replace:
s=s.replace('old', 'new')
s=s{:3]+'xx'+S[5:] # more powerful

build new text with formmating expressions
'That is %d %s bird!" % (1, 'beautiful')
'That is {0} {1} bird!'.format(1, 'beautiful')

Dictionary based formmating:
'%(qty)d more %(food)s' %{'qty':1, 'food':'spam'}
It is powerful when combined with vars() function

you can convert a string to a list, then making in place modifications
L=list(S)








二维码

扫码加我 拉你入群

请注明:姓名-公司-职位

以便审核进群资格,未注明则拒绝

相关推荐
栏目导航
热门文章
推荐文章

说点什么

分享

扫码加好友,拉您进群
各岗位、行业、专业交流群