问题基本上是如果用户输入的两个字符代码只有字母,那么消息接下来应该包括那两个字母。
如果用户输入的两个字符代码有一些数字或特殊符号那么正在构造的消息应该只附加第一个字符。
例如:
> test = "stack overflow"
> character = raw_input (Please provide a two character code with any
> combination of letters, symbol or numbers: )
character = "AA"
message = "stack overflowAA"
But IF
character = "6k"
message = "stack overflow6"
任何人都知道如何做到这一点?
答案 0 :(得分:0)
我会使用字符串索引来获取第一个字符并检查它是否是.isdigit()
sample_input = '6k'
# Get the first character from the input string
first_character = sample_string[0]
# Check if the first character is a digit
first_char_is_digit = first_character.isdigit()
# Choose how much of the input we want to use
if first_char_is_digit:
my_suffix = first_character
else:
my_suffix = sample_input
# Format our text, inserting our siffix in place of the `%s` placeholder
my_text = 'stackoverflow%s' % my_suffix
# Display text value
print(my_text)
我尽可能地写出来,因为你的问题非常基本,我希望尽可能明白这些步骤。如果我写这篇文章,我会像这样压缩它:
sample_input = '6k'
if sample_string[0].isdigit():
sample_input = sample_input[0]
print('stackoverflow%s' % sample_input)