Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Avoiding quotes while printing strings in Python
When printing strings in Python, we often need to avoid displaying quotes around individual string elements. This is especially useful when working with lists of strings where we want clean, formatted output without the quotation marks that normally appear.
Using join() Method
The join() method combines list elements into a single string using a specified separator. This eliminates quotes around individual elements ?
Example
days = ['Mon', 'Tue', 'Wed']
# The given list
print("The given list is : " + str(days))
print("The formatted output is : ")
print(' ** '.join(days))
The output of the above code is ?
The given list is : ['Mon', 'Tue', 'Wed'] The formatted output is : Mon ** Tue ** Wed
Using sep Parameter in print()
The sep parameter in the print() function allows you to specify a custom separator between multiple arguments ?
Example
days = ['Mon', 'Tue', 'Wed']
# The given list
print("The given list is :", days)
print("The formatted output is :")
print(*days, sep=' - ')
The output of the above code is ?
The given list is : ['Mon', 'Tue', 'Wed'] The formatted output is : Mon - Tue - Wed
Using Unpacking with Different Separators
You can use the unpacking operator * with various separators to create different formatting styles ?
Example
days = ['Mon', 'Tue', 'Wed']
print("Space separated:", *days)
print("Comma separated:", *days, sep=', ')
print("Pipe separated:", *days, sep=' | ')
print("No separator:", *days, sep='')
The output of the above code is ?
Space separated: Mon Tue Wed Comma separated: Mon, Tue, Wed Pipe separated: Mon | Tue | Wed No separator: MonTueWed
Comparison
| Method | Use Case | Flexibility |
|---|---|---|
join() |
Single string output | Works with any string separator |
sep parameter |
Direct printing | Simple separators |
Unpacking (*) |
Multiple arguments | Most flexible for print() |
Conclusion
Use join() when you need a formatted string for further processing. Use the sep parameter with unpacking (*) for direct printing with custom separators.
