如何进行字符串处理
字符串的格式化
str1 =
"version"
num =
1.0
format =
"% s" % str1
print format
format =
"% s % d" % (str1, num)
print format
version
version 1
word =
"version3.0"
print word.center(
20)
print word.center(
20,
"*")
print word.ljust(
0)
print word.rjust(
20)
print "% 30s" %word
version3.0
*****version3.0*****
version3.0
version3.0
version3.0
字符串的转义符
path =
"hello\tworld\n"
print path
print len(path)
path =
r"hello\tworld\n"
print path
print len(path)
hello world
12
hello\tworld\n
14
word =
"\thello world\n"
print "direct output:", word
print "after strip(): ", word.strip()
print "after lstrip(): ", word.lstrip()
print "after rstrip(): ", word.rstrip()
direct output: hello world
after strip(): hello world
after lstrip(): hello world
after rstrip(): hello world
字符串的合并
str1 =
"hello "
str2 =
"world "
str3 =
"hello "
str4 =
"China "
result = str1 + str2 + str3
result += str4
print result
hello world hello China
strs = [
"hello ",
"world ",
"hello ",
"China "]
result =
"".join(strs)
print result
hello world hello China
import operator
strs = [
"hello ",
"world ",
"hello ",
"China "]
result = reduce(operator.add, strs,
"")
print result
hello world hello China
字符串的截取
word =
"world"
print word[
4]
d
word =
"world"
str1 =
"hello world"
print word[
0:
3]
print str1[::
2]
print str1[
1::
2]
wor
hlowrd
el ol
sentence =
"Bob said: 1,2,3,4"
print "blankspace split:", sentence.split()
print "comma split:", sentence.split(
",")
print "two comma split:", sentence.split(
",",
2)
blankspace split: ['Bob', 'said:', '1,2,3,4']
comma split: ['Bob said: 1', '2', '3', '4']
two comma split: ['Bob said: 1', '2', '3,4']
str1 =
"a"
print id(str1)
print id(str1+
"b")
55656496
86005960
字符串的比较
str1 =
1
str2 =
"1"
if str1 == str2:
print "same"
else:
print "diff"
if str(str1) == str2:
print "same"
else:
print "diff"
diff
same
word =
"hello world"
print "hello" == word[
0:
5]
print word.startswith(
"hello")
print word.endswith(
"ld",
6)
print word.endswith(
"ld",
6,
10)
print word.endswith(
"ld",
6, len(word))
True
True
True
False
True
字符串的反转
def reverse(s):
out =
""
li = list(s)
for i
in range(len(li),
0,-
1):
out +=
"".join(li[i-
1])
return out
print reverse(
"hello")
olleh
def reverse(s):
out =
""
li = list(s)
li.reverse()
s =
"".join(li)
return s
print reverse(
"hello")
olleh
def reverse(s):
return s[::-
1]
print reverse(
"hello")
olleh
字符串的查找和替换
sentence =
"This is a apple."
print sentence.find(
"a")
sentence =
"This is a apple."
print sentence.rfind(
"a")
8
10
sentence =
"hello world, hello China"
print sentence.replace(
"hello",
"hi")
print sentence.replace(
"hello",
"hi",
1)
print sentence.replace(
"abc",
"hi")
hi world, hi China
hi world, hello China
hello world, hello China
字符串与日期的转换
import time, datetime
print time.strftime(
"%Y-%m-%d %X", time.localtime())
t = time.strptime(
"2008-08-08",
"%Y-%m-%d")
y,m,d=t[
0:
3]
print datetime.datetime(y,m,d)
2017-06-08 15:26:35
2008-08-08 00:00:00