在 Python 中的某个字符处对字符串进行切片
Slice a string at a certain character in Python
要在特定字符处对字符串进行切片:
- 使用该
str.split()
方法在字符上拆分字符串。 - 访问给定索引处的列表。
- 例如,
first = my_str.split('_')[0]
。
my_str = 'bobby_hadz_com' first = my_str.split('_')[0] print(first) # 👉️ bobby second = my_str.split('_')[1] print(second) # 👉️ hadz # --------------------------------- # 👇️ only split string once first, second = my_str.split('_', 1) print(first) # 👉️ bobby print(second) # 👉️ hadz_com
我们使用该str.split()
方法在给定字符处对字符串进行切片。
str.split ()
方法使用定界符将字符串拆分为子字符串列表。
my_str = 'bobby_hadz_com' print(my_str.split('_')) # 👉️ ['bobby', 'hadz', 'com']
该方法采用以下 2 个参数:
姓名 | 描述 |
---|---|
分隔器 | 在每次出现分隔符时将字符串拆分为子字符串 |
最大分裂 | 最多maxsplit 完成拆分(可选) |
If the separator is not found in the string, a list containing only 1 element is
returned.
We split the string on each underscore in the example, but you can use any other
character.
If you only need to split the string once, set the maxsplit
argument to 1
in
the call to str.split()
.
my_str = 'bobby_hadz_com' first, second = my_str.split('_', 1) print(first) # 👉️ bobby print(second) # 👉️ hadz_com
The maxsplit
argument can be used to only split the string on the first
occurrence of the given character.
my_str = 'bobby_hadz_com' # 👇️ ['bobby', 'hadz_com'] print(my_str.split('_', 1))
Note that the str.split()
method returns a list containing a single item if
the character is not in the string.
my_str = 'bobby_hadz_com' print(my_str.split('@')) # 👉️ ['bobby_hadz_com']
You can use the in
operator to check if the character is present in the
string.
my_str = 'bobby_hadz_com' if '_' in my_str: my_list = my_str.split('_') first = my_list[0] print(first) # 👉️ bobby second = my_list[1] print(second) # 👉️ hadz
The
in operator
tests for membership. For example, x in s
evaluates to True
if x
is a
member of s
, otherwise it evaluates to False
.