【脚本语言系列】关于Python基础知识处理字符串,你需要知道的事

本文详细介绍了字符串处理的基础知识,包括格式化、对齐、转义、合并、截取、比较、反转及查找替换等操作,并展示了如何实现这些功能的具体代码实例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

如何进行字符串处理

字符串的格式化

# -*- coding: utf-8 -*-
# format the string
str1 = "version"
num = 1.0
format = "% s" % str1
print format
format = "% s % d" % (str1, num)
print format
version
version  1
# -*- coding: utf-8 -*-
# align the string
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

字符串的转义符

# -*- coding: utf-8 -*-
# print the escape character
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
# -*- coding: utf-8 -*-
# remove the escape character
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

字符串的合并

# -*- coding: utf-8 -*-
# connect the string
str1 = "hello "
str2 = "world "
str3 = "hello "
str4 = "China "
result = str1 + str2 + str3
result += str4
print result
hello world hello China 
# -*- coding: utf-8 -*-
# connect the string
strs = ["hello ", "world ", "hello ", "China "]
result = "".join(strs)
print result
hello world hello China 
# -*- coding: utf-8 -*-
# connect the string
import operator
strs = ["hello ", "world ", "hello ", "China "]
result = reduce(operator.add, strs, "")
print result
hello world hello China 

字符串的截取

# -*- coding: utf-8 -*-
# split the string
word = "world"
print word[4]
d
# -*- coding: utf-8 -*-
# split the string
word = "world"
str1 = "hello world"
print word[0:3]     
print str1[::2]
print str1[1::2]
wor
hlowrd
el ol
# -*- coding: utf-8 -*-
# split the string
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']
# -*- coding: utf-8 -*-
# create new space
str1 = "a"
print id(str1)
print id(str1+"b")
55656496
86005960

字符串的比较

# -*- coding: utf-8 -*-
# compare the string
str1 = 1
str2 = "1"
if str1 == str2:
    print "same"
else:
    print "diff"
if str(str1) == str2:
    print "same"
else:
    print "diff"
diff
same
# -*- coding: utf-8 -*-
# compare the string
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

字符串的反转

# -*- coding: utf-8 -*-
# reverse the string
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
# -*- coding: utf-8 -*-
# reverse the string
def reverse(s):
    out = ""
    li = list(s)
    li.reverse()
    s = "".join(li)
    return s
print reverse("hello")
olleh
# -*- coding: utf-8 -*-
# reverse the string
def reverse(s):
    return s[::-1]
print reverse("hello")
olleh

字符串的查找和替换

# -*- coding: utf-8 -*-
# find the string
sentence = "This is a apple."
print sentence.find("a")
sentence = "This is a apple."
print sentence.rfind("a")
8
10
# -*- coding: utf-8 -*-
# replace the string
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

字符串与日期的转换

# -*- coding: utf-8 -*-
# convert between string and time
import time, datetime

# time to string
print time.strftime("%Y-%m-%d %X", time.localtime())
# string to time
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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值