如何提取用戶輸入的名稱的前半部分和後半部分?我已經將名稱分開,以便我有一個列表,並已設置變量firstName
和lastName
。如果名字有奇數字母,則中間字母爲不包括,但如果第二個名字有奇數字母,則中間字母爲,包括。我怎樣才能做到這一點?從Python中的字符串中提取字符
示例名稱:
- 瑪麗·莫爾斯 - > Marse
- 洛根彼得斯 - > Loers
- 梅根Hufner - > Megner
如何提取用戶輸入的名稱的前半部分和後半部分?我已經將名稱分開,以便我有一個列表,並已設置變量firstName
和lastName
。如果名字有奇數字母,則中間字母爲不包括,但如果第二個名字有奇數字母,則中間字母爲,包括。我怎樣才能做到這一點?從Python中的字符串中提取字符
示例名稱:
這樣的事情可能會爲你工作:
>>> 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'
這工作!非常感謝!!我只需要將它工作到該功能,但它的工作! – katherinethegrape
@katherinethegrape ...你可以向S.O.證明。社區通過接受這個答案。 –
您必須命名每個姓氏和名字作爲字符串變量並執行以下操作:
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
正在發生的事情真的是你使用的是flooring
或ceiling
師。要獲得一個數字的ceiling
,您可以使用math.ceil()
函數。以下是對Python3的一點矯枉過正,但我使用int(math.ceil...)
,因爲在Python2中,math.ceil()
返回一個浮點數。我也使用len(last)/2.
,因爲在Python2中,整數除以整數總是導致整數。 (地板分區)。接下來假設firstName
和lastName
已經定義:
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:])
怎麼樣代碼反映你的try ...用實例說明你的輸入和預期的輸出? –
示例輸入和輸出將*真的*有用。 – zondo
@zondo例子在! – katherinethegrape