2016-02-24 35 views
-1

如何提取用户输入的名称的前半部分和后半部分?我已经将名称分开,以便我有一个列表,并已设置变量firstNamelastName。如果名字有奇数字母,则中间字母为不包括,但如果第二个名字有奇数字母,则中间字母为,包括。我怎样才能做到这一点?从Python中的字符串中提取字符

示例名称:

  • 玛丽·莫尔斯 - > Marse
  • 洛根彼得斯 - > Loers
  • 梅根Hufner - > Megner
+4

怎么样代码反映你的try ...用实例说明你的输入和预期的输出? –

+2

示例输入和输出将*真的*有用。 – zondo

+0

@zondo例子在! – katherinethegrape

回答

0

这样的事情可能会为你工作:

>>> def concatenate(s): 
     s1,s2 = s.split() 
     i,j = len(s1)//2, len(s2)//2 
     return s1[:i]+s2[j:] 

>>> s = 'Meghan Hufner' 
>>> concatenate(s) 
'Megner' 
>>> s = 'Helen Paige' 
>>> concatenate(s) 
'Heige' 
>>> s = 'Marie Morse' 
>>> concatenate(s) 
'Marse' 
>>> s = 'Logan Peters' 
>>> concatenate(s) 
'Loers' 
+0

这工作!非常感谢!!我只需要将它工作到该功能,但它的工作! – katherinethegrape

+0

@katherinethegrape ...你可以向S.O.证明。社区通过接受这个答案。 –

0

您必须命名每个姓氏和名字作为字符串变量并执行以下操作:

first = 'Marie' 
last = 'Morse' 
first_index = len(first)/2 +1 
last_index = len(last)/2 
result = first[:first_index] + last[last_index+1:] 
print result 
0

正在发生的事情真的是你使用的是flooringceiling师。要获得一个数字的ceiling,您可以使用math.ceil()函数。以下是对Python3的一点矫枉过正,但我​​使用int(math.ceil...),因为在Python2中,math.ceil()返回一个浮点数。我也使用len(last)/2.,因为在Python2中,整数除以整数总是导致整数。 (地板分区)。接下来假设firstNamelastName已经定义:

import math 

first_index = len(firstName) // 2    # floor division 
last_index = int(math.ceil(len(lastName)/2.)) # ceiling division 

print(first[:first_index] + last[-last_index:])