Select to view content in your preferred language

help inserting simple characters

1284
8
Jump to solution
03-06-2022 10:02 AM
Chelsea_Trusdell
Emerging Contributor
 
0 Kudos
5 Solutions

Accepted Solutions
DanPatterson
MVP Esteemed Contributor
"".join([f"_{i}" for i in "hello"])+"_"
 '_h_e_l_l_o_'

... sort of retired...

View solution in original post

0 Kudos
AndyAnderson
Frequent Contributor

Look into Python’s assignment operators.

View solution in original post

0 Kudos
DavidPike
MVP Frequent Contributor

perhaps missing the augmented assignment operator +=

word = "hello"
new_word = "_"
for letter in word:
  new_word += letter + "_"
print(new_word)

View solution in original post

JoshuaBixby
MVP Esteemed Contributor

Similar, but slightly different, to another response using str.join() and string formatting:

>>> word = "hello"
>>> print(f"_{'_'.join(word)}_")
_h_e_l_l_o_
>>> 

View solution in original post

0 Kudos
by Anonymous User
Not applicable

To avoid leading and trailing join symbols, you can try this:

word = "hello"
joinword = ""

for (idx,letter) in enumerate(word):
   joinword += letter
   if idx < len(word)-1:
      joinword += "_"

print(joinword)

This will print 'h_e_l_l_o'

View solution in original post

0 Kudos
8 Replies
DanPatterson
MVP Esteemed Contributor
"".join([f"_{i}" for i in "hello"])+"_"
 '_h_e_l_l_o_'

... sort of retired...
0 Kudos
Chelsea_Trusdell
Emerging Contributor

For example, for a string hello, the result should be _h_e_l_l_o_.

word = "hello"
new_word = "_"
for letter in word:
new_word = letter + "_"
print(new_word)

 

but i am not getting _h_e_l_l_o_. this. what am i doing wrong ? how do i fix this ?

thanks 

 

0 Kudos
AndyAnderson
Frequent Contributor

Look into Python’s assignment operators.

0 Kudos
Chelsea_Trusdell
Emerging Contributor

For example, for a string hello, the result should be _h_e_l_l_o_.

word = "hello"
new_word = "_"
for letter in word:
new_word = letter + "_"
print(new_word)

 

but i am not getting _h_e_l_l_o_. this. what am i doing wrong ?

thanks 

0 Kudos
DavidPike
MVP Frequent Contributor

perhaps missing the augmented assignment operator +=

word = "hello"
new_word = "_"
for letter in word:
  new_word += letter + "_"
print(new_word)
JoshuaBixby
MVP Esteemed Contributor

Similar, but slightly different, to another response using str.join() and string formatting:

>>> word = "hello"
>>> print(f"_{'_'.join(word)}_")
_h_e_l_l_o_
>>> 
0 Kudos
Chelsea_Trusdell
Emerging Contributor

thank you both!

0 Kudos
by Anonymous User
Not applicable

To avoid leading and trailing join symbols, you can try this:

word = "hello"
joinword = ""

for (idx,letter) in enumerate(word):
   joinword += letter
   if idx < len(word)-1:
      joinword += "_"

print(joinword)

This will print 'h_e_l_l_o'

0 Kudos