How to assign a variable depending on a certain value in Python

时间:2018-03-23 00:21:31

标签: python

I'm trying to create a program that involves assigning a string to the variable x depending on the length of the string assigned to variable y. The amount of commas in x should be the same as the length of y.

For example if e='h' , x=','. If e='hi' , x=',,'. If e='him' , x=',,,'

By the way, I'm new to programming so I don't know this stuff.

2 个答案:

答案 0 :(得分:2)

Invoke len() on e to get the length of the string and multiply that length by the string ,, assigning it to x:

e = 'him'
e_length = len(e)
x = ',' * e_length
print(x)

This should yield ,,,.

答案 1 :(得分:1)

Python allows you to multiply a string by a number to repeat it, which means you can do:

e = 'hello there'
x = ',' * len(e)

Which will give you:

',,,,,,,,,,,'