Cut Python String

Asked 2 years ago, Updated 2 years ago, 79 views

You are a Python user.

For example, if you have the string a="apple,banana,cow",

print_1="apple" print_2="banana" print_3="cow"

How do you create a code that stores it like this?

(It's a beginner. I look forward to your kind cooperation.)

python string slice

2022-09-21 16:49

2 Answers

Python manages variable management as dict type.

It's important to manage it with a dict type.

a = "apple,banana,cow"
varTemplate = "print_{}"

for i, v in enumerate(a.split(',')):
    globals()[varTemplate.format(i)] = v


print_0
Out[29]: 'apple'

print_1
Out[30]: 'banana'

print_2
Out[31]: 'cow'


2022-09-21 16:49

a="apple,banana,cow"
print_1, print_2, print_3 = a.split(',')

print_1
Out[11]: 'apple'

print_2
Out[12]: 'banana'

print_3
Out[13]: 'cow'


2022-09-21 16:49

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.