简体   繁体   中英

Python: Split Input Text into {Letter}

Let's say I have an Input 'Apple'. How do I make it split into {A}{p}{p}{l}{e}? The letters stand for variables here which are used in a code that prints out at the end.

Edit: I am currently trying to learn python, so there is no special usecase for what I want to do. But actually all I want is that a user inputs the word "Apple" and he gets 5 words out of it. Like A stands for "Hello" etc. I assigned already the variables. From what I know code = f'{A}' would print out Apple then. so I need the input splitted to each letter one by one with {} around it.

Use f-strings!

your_string = 'Apple'
new_string = "".join([f"{{{s}}}" for s in your_string])

Using F-strings, you can put variables in a string. In this list comprehension we loop over your input string. For every letter in your string, we put it in this weird looking f"{{{s}}}" formatted string. The double {{ is the way to escape a curly brace in f-strings, while a single { starts opening the place where you want your variables to be.

Say you want to do this in python <= 3.5, you could do it in different ways... You could iterate over the string, add the inside curly braces and use string concatenation for the first and last braces.

new_string = "{" + "}{".join([s for s in your_string]) + "}"

The last and probably the most readable, but slower way is using a simple for-loop

new_string = ""
for letter in your_string:
    new_string += "{" + letter + "}"

There's no dynamic variable naming in Python, but for this case you can use a dictinary to store whatever you like under the names of your letters:

bar = {}
foo = 'Apple'
for l in foo:
    bar[l] = l
print(bar)

will make a dictionary of keys corresponsing to your letters, which contain your letters, hence the print(bar) will output: {'A': 'A', 'p': 'p', 'l': 'l', 'e': 'e'}

Since the string is already an array of sort you can simply iterate through it:

string = 'apple'
for char in string:
    print(char)

Output:
a
p
p
l
e
>>> w = list('Apple') #['A', 'p', 'p', 'l', 'e']
>>> print(''.join(['{' + i + '}' for i in w]))
{A}{p}{p}{l}{e}
>>> print(''.join([f'{{{i}}}' for i in 'Apple']))
{A}{p}{p}{l}{e}
["{}{}{}".format("{", letter, "}") for letter in list("Apple")]

You can do it like this:

text="Apple"
stext=list(text) #split character in "text" string into list of character and store the list in "stext"

or directly:

stext=list("Apple")

or even simple:

print(list("Apple"))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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