1

I have a string like: project = '1,2' and I want to insert another number to this string. So for example after the insertion I want to have : project = '1,2,3' Could you please help me?

Thanks

4 Answers 4

2

Another option is str.join():

project = '1,2'
n = 3
project = ','.join((project, str(n)))
Sign up to request clarification or add additional context in comments.

Comments

2

.format should help you.

project = "1,2"
project += ',{}'.format(3)

And if you have a position, you could use slicing :

project = "1,2,4,5"

position = 3

project = project[:position] + ',3' + project[position:]

EDIT

I thought about another solution:

project += '%s%s' % (',',3)

2 Comments

didn't notice you actually posted this before me. I'll get rid of mine. +1
The simplest solution tends to be the right one. ;-)
0

Just convert the number into string using str() and append division symbol and the number you want to insert

project = "1,2"
project += ',' + str(3)
print (project)

Comments

-1

You can convert it to a list with numbers = project.split(","). You can then add another number with numbers.append('3'). Then make a new string with newproject = ",".join(numbers). Full code:

project = "1,2"
numbers = project.split(",")
numbers.append('3')
newproject = ",".join(numbers)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.