我想选择用户输入的首字母并将其用于循环决策。一个简单的例子:
cat
程序应将“是”检测为“ Y”,将“否”检测为“ N”。
答案 0 :(得分:1)
要选择第一个字母,只需在输入后添加[0]
。 [0]
是字符串切片-在这里它仅提取字符串的第一个字符。还要注意,所有以'Y'
开头的输入都将被视为“是”输出,而所有以'N'
开头的输入都将被视为“否”输出。
play_again = input("Do you want to play again? (y/n)").lower()
# Simply add [0]. But that does not work for empty strings.
if len(play_again) > 0)
play_again = play_again[0]
请注意,如果您提供的输入为空,则该方法将不起作用-否则将导致回溯声明IndexError: string index out of range
。这就是为什么要有一个if语句的原因。
示例:
Do you want to play again? (y/n)YES
y
Do you want to play again? (y/n)no
n
Do you want to play again? (y/n)OMG
o
Do you want to play again? (y/n)yakety yak
y
Do you want to play again? (y/n)
#Empty String
答案 1 :(得分:0)
play_again = input("Do you want to play again? (y/n)").lower()
if play_again in ['yes', 'no', 'y', 'n']:
play_again = play_again[0]
if play_again == 'y':
# do something
else:
# do something else
答案 2 :(得分:0)
字符串索引类似于Python中的列表索引。因此,您可以直接索引第0个元素:
play_again = input('Do you want to play again? (y/n)')[0].lower()
例如:
Do you want to play again? (y/n)Yes
print(play_again)
'y'
答案 3 :(得分:0)
play_again = input("Do you want to play again? (y/n)").lower()
first_letter=play_again[0]
#or
play_again = input("Do you want to play again? (y/n)").lower()[0]
答案 4 :(得分:0)
我认为这正是您想要的:
<html>
<head>
<script type="text/javascript" src="https://platform.linkedin.com/in.js">
api_key: [MY KEY] //Client ID
onLoad: OnLinkedInFrameworkLoad //Method that will be called on page load
authorize: true
</script>
</head>
<script type="text/javascript">
function OnLinkedInFrameworkLoad() {
console.log('OnLinkedInFrameworkLoad');
IN.Event.on(IN, "auth", OnLinkedInAuth);
}
function OnLinkedInAuth() {
console.log('OnLinkedInAuth');
IN.API.Profile("me").result(ShowProfileData);
}
function ShowProfileData(profiles) {
console.log('ShowProfileData' + profiles);
var member = profiles.values[0];
var id = member.id;
var firstName = member.firstName;
var lastName = member.lastName;
var photo = member.pictureUrl;
var headline = member.headline;
//use information captured above
var stringToBind = "<p>First Name: " + firstName + " <p/><p> Last Name: "
+ lastName + "<p/><p>User ID: " + id + " and Head Line Provided: " + headline
+ "<p/>"
document.getElementById('profiles').innerHTML = stringToBind;
}
</script>
<body>
<div id="profiles"></div>
</body>
</html>
说明:
play_again = input('Do you want to play again? (y/n)')[0].lower()
while(play_again=='y'):
# Do something
play_again = input('Do you want to play again? (y/n)')[0].lower()
从输入字符串中提取第一个字母,[0]
会将字符标准化为小写,例如。 Y 或 y 到 y , N 或 n 到 n < / strong>。
如果用户输入的字符串以 Y 或 y 开头,则.lower()
循环触发器是第一次,并一直循环直到重复如此。中断条件是输入字符串不以 Y 或 y 开头。