Python3 字符串操作

本文介绍了Python3中的字符串操作,包括变量插入、内置方法、字符串复制、反转、拼接、比较、正则表达式匹配以及各种字符串方法如capitalize、casefold、center、count、endswith等。此外,还探讨了正则表达式的使用,如search和子串提取。

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

字符串中嵌入变量

# Python3
>>> name1 = "Joe"
>>> name2 = "Mary"
>>> print(f"你好 {name1}, {name2} 在哪?")
你好 Joe, Mary 在哪?

字符串内建方法

# Python3
>>> myStr = str("THIS IS TEST")
>>> myStr
'THIS IS TEST'
>>> foo = myStr.lower()
>>> foo
'this is test'

字符串自我复制

# Python3
>>> aa = "hello world"
>>> aa * 3
'hello worldhello worldhello world'

字符串反转

一般来说,下面三种反转字符串的方式用的比较多。

>>> aa = "hello world"
>>> ''.join(reversed(aa))
'dlrow olleh'
>>> aa[::-1]
'dlrow olleh'
>>> reduce(lambda x, y: y + x, aa)
'dlrow olleh'

字符串拼接

# Python3
>>> "hello" + " world"
'hello world'

字符串比较

# Python3
>>> "hello" < "world"
True
>>> 0 if "hello" == "world" else (-1 if "hello" < "world" else 1)
-1
>>> "hello" == "world"
False
# Ruby
[13] pry(main)> "hello" < "world"
=> true
[14] pry(main)> "hello" <=> "world"
=> -1
[15] pry(main)> "hello" == "world"
=> false

正则表达式匹配

# Python3
>>> import re
>>> re.search("ll", "hello world")
<_sre.SRE_Match object; span=(2, 4), match='ll'>
>>> re.search("o.*o", "hello world")
<_sre.SRE_Match object; span=(4, 8), match='o wo'>

字符串子串

# Python3
>>> "hello world"[0:5]
'hello'
>>> "hello world"[0:-6]
'hello'

str.capitalize()

# Python3
>>> aa = "hello world"
>>> aa.capitalize()
'Hello world'

str.casefold()

和 lower() 比较像,casefold 支持很多不同种类的语言。比如说 β。str.lower() 只能显示出原形而 casefold 则能显示他的小写。

# Python3
>>> "Hello woRld ß".casefold()
'hello world ss'
>>> "Hello woRld .ß".lower()
'hello world ß'

str.center(width, fillchar)

# Python3
>>> aa = "hello world"
>>> aa.center(20)
'    hello world     '
>>> aa.center(20, '*')
'****hello world*****'

str.count(substr) 

# Python3
>>> "hello world".count('o')
2

str.endwiths(suffix)

# Python3
>>> aa = "hello world"
>>> aa.endswith("ld")
True
>>> aa.endswith("l")
False

str.expandtabs()

用空格将制表符 \t 填充替换到指定的长度

>>> '01\t012\t0123\t01234'.expandtabs()
'01      012     0123    01234'
>>> '01\t012\t0123\t01234'.expandtabs(16)
'01              012             0123            01234'

str.index(substr)

跟 find() 方法一样,只不过如果 substr 不在字符串中会报一个异常。

# Python3
>>> aa = "hello world"
>>> aa.find('o')
4
>>> aa.index('o')
4
>>> aa.index('ol')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: substring not found
>>> aa.find('ol')
-1

str.isalnum()

# Python3
>>> aa = "hello world"
>>> aa.isalnum()
False
>>> aa = "helloworld5"
>>> aa.isalnum()
True

str.isalpha()

# Python3
>>> aa = "helloworld"
>>> aa.isalpha()
True
>>> aa = "hello world"
>>> aa.isalpha()
False

str.isdigit()

str.isdigit() 检测字符串是否只包含数字(即不接受其他一切非 [0-9] 元素)。

# Python3
>>> aa = "hello world"
>>> aa.isdigit()
False
>>> aa = "12345"
>>> aa.isdigit()
True

str.isnumeric()

# Python3
>>> "12345Ⅲ".isnumeric()
True
>>> "12345.67".isnumeric()
False

str.islower()

# Python3
>>> "hello world".islower()
True
>>> "Hello world".islower()
False

str.isupper()

# Python3
>>> "hello world".isupper()
False
>>> "HELLO WORLD".isupper()
True

str.isspace()

# Python3
>>> "hello world".isspace()
False
>>> "       ".isspace()
True

str.istitle()

# Python3
>>> "hello world".istitle()
False
>>> "Hello World".istitle()
True

str.isdecimal()

# Python3
>>> "2345".isdecimal()
True
>>> "0aff".isdecimal()
False

str.join(seq)

# Python3
>>> aa = ['h', 'e', 'l', 'l', 'o']
>>> "".join(aa)
'hello'
>>> "-".join(aa)
'h-e-l-l-o'

str.ljust(20)

# Python3
>>> "hello world".ljust(20)
'hello world         '
>>> "hello world".ljust(20, '-')
'hello world---------'

str.lstrip()

# Python3
>>> "  hello world".lstrip()
'hello world'

str.lower()

# Python3
>>> "Hello World".lower()
'hello world'

str.replace(old, new [, max])

# Python3
>>> "hello world".replace("world", "hello")
'hello hello'

str.rjust(20)

如果是要在左边填充 0 的话, zfill 也是很不错的选择。

# Python3
>>> "hello world".rjust(20)
'         hello world'
>>> "hello world".rjust(20, '-')
'---------hello world'

str.rstrip()

# Python3
>>> "hello world  ".rstrip()
'hello world'

str.strip()

# Python3
>>> "  hello world  ".strip()
'hello world'

str.partition(seperator)

# Python3
>>> "hello world !".partition(' ')
('hello', ' ', 'world !')

str.split(seperator)

# Python3
>>> "hello world".split()
['hello', 'world']
>>> "hello world".split('l')
['he', '', 'o wor', 'd']
>>> "hello world".split('l', 2)
['he', '', 'o world']

str.startswith(prefix)

# Python3
>>> "hello world".startswith("hello")
True

str.swapcase()

# Python3
>>> "Hello World".swapcase()
'hELLO wORLD'

str.title()

# Python3
>>> "hello world".title()
'Hello World'

str.upper()

# Python3
>>> "Hello World".upper()
'HELLO WORLD'

str.zfill(num)

# Python3
>>> "10110".zfill(8)
'00010110'

len(str)

# Python3
>>> len("hello world")
11

max(str)

# Python3
>>> max("hello world")
'w'

min(str)

# Python3
>>> min("hello world")
' '
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值