Python 片字符串

Python 字符串支持剪切以创建子字符串. 请注意,Python 字符串是不可变的,剪切会从源字符串创建一个新的子字符串,而原始字符串保持不变。

Python 的 Slic String

Python 的 slice string 语法是:

1str_object[start_pos:end_pos:step]

剪切以 start_pos 索引(包含)开始,以 end_pos 索引(排除)结束。步骤参数用于指定从 start 到 end 索引所需的步骤。 Python String 剪切总是遵循这个规则: s[:i] + s[i:] == s 对于任何索引i都是可选的。

1s = 'HelloWorld'
2
3print(s[:])
4
5print(s[::])

输出:

1HelloWorld
2HelloWorld

请注意,由于没有提供切割参数,所以底线等于原始字符串,让我们看看切割字符串的更多例子。

1s = 'HelloWorld'
2first_five_chars = s[:5]
3print(first_five_chars)
4
5third_to_fifth_chars = s[2:5]
6print(third_to_fifth_chars)

输出:

1Hello
2llo

请注意,索引值从 0 开始,因此 start_pos 2 是指字符串中的第三个字符。

使用 Slicing 扭转一个字符串

我们可以使用切割来扭转一个字符串,将步骤值作为 -1.

1s = 'HelloWorld'
2reverse_str = s[::-1]
3print(reverse_str)

输出: dlroWolleH 让我们看看一些其他使用步骤和负索引值的例子。

1s1 = s[2:8:2]
2print(s1)

输出: loo 在这里,字符串包含指数 2.4 和 6 的字符。

1s1 = s[8:1:-1]
2print(s1)

Output: lroWoll Here the index values are taken from end to start. The substring is made from indexes 1 to 7 from end to start. python slice string

1s1 = s[8:1:-2]
2print(s1)

Output: lool python slice string reverse Python slice works with negative indexes too, in that case, the start_pos is excluded and end_pos is included in the substring.

1s1 = s[-4:-2]
2print(s1)

Output: or python string slicing substring negative index Python string slicing handles out of range indexes gracefully.

1>>>s = 'Python'
2>>>s[100:]
3''
4>>>s[2:50]
5'thon'

这就是 python 字符串切片函数来创建字符串的全部。

您可以从我们的 GitHub 存储库中查阅完整的 Python 脚本和更多 Python 示例。

Published At
Categories with 技术
Tagged with
comments powered by Disqus