📜  Python|将给定的字符串分成相等的两半

📅  最后修改于: 2022-05-13 01:55:35.584000             🧑  作者: Mango

Python|将给定的字符串分成相等的两半

有时,我们需要简单地将字符串分成相等的两半。这种类型的应用程序可以出现在从简单编程到 Web 开发的各个领域。让我们讨论可以执行此操作的某些方式。

方法#1:使用列表理解+字符串切片
这是执行此特定任务的幼稚方法。在这里,我们只使用暴力分割和切片来分隔字符串的第一部分和最后一部分。

# Python3 code to demonstrate working of
# Splitting string into equal halves
# Using list comprehension + string slicing
  
# initializing string 
test_str = "GeeksforGeeks"
  
# printing original string 
print("The original string is : " + test_str)
  
# Using list comprehension + string slicing
# Splitting string into equal halves
res_first = test_str[0:len(test_str)//2]
res_second = test_str[len(test_str)//2 if len(test_str)%2 == 0
                                 else ((len(test_str)//2)+1):]
  
# printing result 
print("The first part of string : " + res_first)
print("The second part of string : " + res_second)
输出 :
The original string is : GeeksforGeeks
The first part of string : Geeksf
The second part of string : rGeeks

方法#2:使用字符串切片
为了克服上述方法的缺点并找到更优雅的解决方案,我们使用字符串切片来执行此特定任务。

# Python3 code to demonstrate working of
# Splitting string into equal halves
# Using string slicing
  
# initializing string 
test_str = "GeeksforGeeks"
  
# printing original string 
print("The original string is : " + test_str)
  
# Using string slicing
# Splitting string into equal halves
res_first, res_second = test_str[:len(test_str)//2], 
                        test_str[len(test_str)//2:]
  
# printing result 
print("The first part of string : " + res_first)
print("The second part of string : " + res_second)
输出 :
The original string is : GeeksforGeeks
The first part of string : Geeksf
The second part of string : orGeeks