程序:输入名称并打印姓名缩写和姓氏。
输入: - Ted Vivian Mosby
输出: - T V Mosby
使用Python 3在线编译器: -
https://repl.it/languages/python3
user = input('Please Enter your name \n')
length = len(user)
value=0
for a in range(0,length-1):
if a==" ":
value=a
for b in range(0,value):
if b==0:
print(user[0])
elif user[b]==" ":
print(user[b+1])
for c in range(value+1,length):
print(user[c])
我的输出是: -
请输入您的姓名
Ted Vivian Mosby
Ë
d
V
我
v
我
一个
n
中号
Ø
小号
b
y
答案 0 :(得分:1)
这是一种pythonic方式。请注意,无论中间名有多少,它都会考虑所有名称。
name = input("Please enter a name: ")
names = name.split()
initials = [x[0] for x in names[:-1]]
print(*initials, names[-1])
"""
Broken down:
name.split() = ['Ted', 'David', 'Vivican', 'Mosby'] Note ive added an extra name for show
name.split()[:-1] = ['Ted', 'David', 'Vivican']
[x[0] for name in ['Ted', 'David', 'Vivican']] = ['T', 'D', 'V']
print(*initials) unpacks each value in the list to the function eg
print(*['T', 'D', 'V']) == print('T', 'D', 'V')
"""
答案 1 :(得分:0)
使用split()
分隔名称。然后打印每个名字的第一个字符,但是打印整个姓氏。
user = input('Please Enter your name \n')
names = user.split()
for i in range(0, len(names)):
if i < len(names) - 1:
# print first char only, no newline at the end
print(names[i][0], end=" ")
else:
# print entire last name
print(names[i]) # print entire name
答案 2 :(得分:-1)
user = input('Please Enter your name \n')
length = len(user.split(" "))
value=0
print(length)
for a in user.split(" "):
if(value==length-1):
print(a)
else:
print(a[0],end=' ')
value+=1