简体   繁体   English

我将如何执行呢? 蟒蛇

[英]How would I execute this? Python

I am pretty new to python and would like to know how to write a program that asks the user to enter a string that contains the letter "a". 我对python很陌生,想知道如何编写一个程序,要求用户输入包含字母“ a”的字符串。 Then, on the first line, the program should print the part of the string up to and including the certain letter, and on the second line should be the rest of the string. 然后,在第一行中,程序应打印字符串的一部分,直到并包括特定字母,在第二行中,应打印其余部分。 For example... 例如...

Enter a word: Buffalo
Buffa 
lo

This is what I have so far : 这是我到目前为止所拥有的:

text = raw_input("Type something: ")
left_text = text.partition("a")[0]
print left_text

So, I have figured out the first part of printing the string all the way up to the certain letter but then don't know how to print the remaining part of the string. 因此,我已经弄清楚了将字符串一直打印到特定字母的第一部分,但后来又不知道如何打印字符串的其余部分。

Any help would be appreciated 任何帮助,将不胜感激

If what you want is the first occurrence of a certain character, you can use str.find for that. 如果您想要的是某个字符的第一次出现,则可以使用str.find Then, just cur the string into two pieces based on that index! 然后,根据该索引将字符串分成两部分!

In python 3: 在python 3:

split_char = 'a'
text = input()
index = text.find(split_char)
left = text[:-index]
right = text[-index:]
print(left, '\n', right)

I don't have a python2 on hand to make sure, but I assume this should work on python 2: 我手头没有python2来确定,但是我认为这应该可以在python 2上工作:

split_char = 'a'
text = raw_input()
index = text.find(split_char)
left = text[:-index]
right = text[-index:]
print left + '\n' + right)

Another option that is far more concise is to use 更为简洁的另一种选择是使用

left_text, sep, right_text = text.partition("a")
print (left_text + sep, '\n', right_text)

and then as suggested in the comments, thanks @AChampion ! 然后按照评论中的建议,谢谢@AChampion!

You should have some knowledge about slicing and concatenating string or list. 您应该对切片和连接字符串或列表有一些了解。 You can learn them here Slicing and Concatenating 您可以在此处学习切片和级联

word = raw_input('Enter word:')  # raw_input in python 2.x and input in python 3.x

split_word = raw_input('Split at: ')

splitting = word.partition(split_word)


'''Here lets assume,

   word = 'buffalo'
   split_word = 'a'

   Then, splitting variable returns list, storing three value,
           ['buff', 'a', 'lo']

   To get your desire output you need to do some slicing and concatenate some value .
'''

output = '{}\n{}'.join(splitting[0] + splitting[1], splitting[2])
print(output) 

First find the indices of the character in the given string, then print the string accordingly using the indices. 首先找到给定字符串中字符的索引,然后使用索引相应地打印字符串。

Python 3 Python 3

string=input("Enter string")
def find(s, ch):
    return [i for i, ltr in enumerate(s) if ltr == ch]
indices=find(string, "a")

for index in indices[::-1]:
    print(string[:index+1])

print(string[indices[-1]+1:])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM