Home > Enterprise >  How to edit the string and add quotes in python [closed]
How to edit the string and add quotes in python [closed]

Time:10-06

I have a problem with split string on python. For example I have a string that need to add some quotes on it.

Example string:

word = "VITAMIN, HEALTH, SPORT"

And edit it to add some quotes on it into like this

word = "'VITAMIN', 'HEALTH', 'SPORT'"

CodePudding user response:

Use:

str(word.split(", "))[1:-1]

Or just do:

"'"   "', '".join(word.split(', '))   "'"

Both solutions output:

'VITAMIN', 'HEALTH', 'SPORT'

Use str.split with str and slicing to remove the brackets.

CodePudding user response:

Just do:

word = ", ".join(f"'{s}'" for s in word.split(", "))
print(word)

Output

'VITAMIN', 'HEALTH', 'SPORT'

CodePudding user response:

You need to escape the quotes with \'. So your code will be -

word = "\'VITAMIN\', \'HEALTH\', \'SPORT\'"

A article on escape characters https://www.w3schools.com/python/gloss_python_escape_characters.asp

CodePudding user response:

One way that uses the fact that str.__repr__ puts a string within single quotes (unless the string contains single quotes):

word = ", ".join(map(repr, word.split(", ")))

Docs on:

  • Related