0

I'm working on a project, currently, and I would like to add characters/gr

barfoo = ""
# Something that adds 'hel' to barfoo?
# Something that adds 'lo' to barfoo?
print(barfoo)
> 'hello'

How would I do such a thing? Note that I am aware of adding it to a list and simply 'condensing' it, but I would like to know if there is an easier method.

8
  • 3
    You can't initialize what's not defined. Commented Jun 12, 2018 at 22:45
  • You could initialise it with an empty string barfoo = "", which would result in hi after appending h and i. However, by assigning the empty string to the variable barfoo, you are defining the variable. Commented Jun 12, 2018 at 22:52
  • I think "I want to initialize a string but not define it" is xXIronmanXx's way of saying that he wants "an empty string" (or initialize barfoo to an empty string). Commented Jun 12, 2018 at 22:55
  • Strings are immutable. You can reassign what a name points to, but not append to a string. Commented Jun 12, 2018 at 23:36
  • So you can't append @ChristophTerasa? Commented Jun 15, 2018 at 22:03

2 Answers 2

5

Either start with an empty string and concatenate, or start with an empty list and join.

barfoo = ''
barfoo += 'h'
barfoo += 'i'
print(barfoo)

...

barfoo = []
barfoo.append('h')
barfoo.append('i')
print(''.join(barfoo))
Sign up to request clarification or add additional context in comments.

2 Comments

I'm sorry, but I thought += and -= was for numbers only
@xXIronmanXx: They are for any type that implements either them or + and -.
2

Here is an example of what you are trying to achieve:

barfoo = ""
barfoo = barfoo + 'H'
barfoo = barfoo + 'I'

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.