Logo

dev-resources.site

for different kinds of informations.

String and Trailing comma, get couple and become, Tuple (): A copy & paste mistake to Error and concept

Published at
7/21/2024
Categories
python
tuple
string
datatype
Author
ajitkumar
Categories
4 categories in total
python
open
tuple
open
string
open
datatype
open
Author
9 person written this
ajitkumar
open
String and Trailing comma, get couple and become, Tuple (): A copy & paste mistake to Error and concept

Today, I am going to tell a story about my copy & paste mistake and how a string with trailing comma get coupled and became a Tuple() in my Python program. Strangely, I was not not aware of this concept before making this mistake.
So, let start with having a quick learning about string and tuple in Python.

String

Definition: A sequence of characters used to store and manipulate text.
Syntax: Enclosed in single quotes ' ', double quotes " ", or triple quotes ''' '''/""" """.
Immutability: Strings cannot be changed after creation.

# Example
mystring = "Hello, World!"
print(type(mystring)) 
#Output: <class 'str'>

mystring2 =str()
print(type(mystring2))
#Output: <class 'str'>
Enter fullscreen mode Exit fullscreen mode

Tuple

Definition: An immutable sequence of values.

Syntax: Defined with parentheses ( ), separated by commas.

Immutability: Once created, elements cannot be changed.

# Example
mytuple = (1,2)
print(type(mytuple)) 
#Output:<class 'tuple'>

mytuple2 =tuple()
print(type(mytuple2))
#Output:<class 'tuple'>
Enter fullscreen mode Exit fullscreen mode

Now, we know about string and tuple and how to get a variable of type string or tuple using either direct assignment or using class approach by using constructor. But, my story is different :).

Python statement do not need a semicolon (;) or comma (,) or any other closing symbol (spacing is used to handle block), so how you can end-up a trailing comma with string like β€œAjit Kumar”, because often you copy string element from list of dictionary and often endup with a trailing comma. This is what happened to me and then story became interesting.

String with Trailing comma

So, first let have an example of my stroy.

mymistake = "Ajit Kumar",
print(type(mymistake))
#Output : <class 'tuple'>
Enter fullscreen mode Exit fullscreen mode

Now, there are two things to observe:
1) Python interpreter will not throw any error due to the trailing comma with the string 'mymistake', otherwise error would have not be go any further.

2) The variable type became 'tuple' than original intention of creating a string variable mymistake.

I wrote here and it seems very easy and simple, but it took hour to debug this error, because i was passing the string as argument to a method and the errors were strange and i keep working on method and trying to understand the error message. For example, the message was like, the 'name' variable don't have a method lower().

Issues

If you use a comma without parentheses, Python treats it as a tuple.

Example: mymistake = "Ajit Kumar", creates a tuple ("Ajit Kumar",).

So, if you want to create a tuple having only item/element, you need to be very careful. Following example, demonstrate that, in first example, even an item is within pair of brackets (1), python treat that as integer and not tuple.

singleitem = (1)
print(type(singleitem))
#Output: <class 'int'>
Enter fullscreen mode Exit fullscreen mode

So, to create tuple with a single item , you must need to use a trailing comma, as follows:

singleitemtuple = (1,)
print(singleitemtuple)
#output:  (1,)

print(type(singleitemtuple))
#output:  <class 'tuple'>
Enter fullscreen mode Exit fullscreen mode

And, i think, this is the reason why when the string having a trailing comma so python takes that as tuple and created the variable as tuple not as string.

However, the Python documentation have mentioned it clearly and it was my mistake or my negligence that i didn't notice it and have been always using () to create a tuple even for a single item with training comma. Source

Anyway, this given me some new learning and a shortcut to create a tuple with single item, or more items without using (). Yes, I went ahead try to use the "trailing comma" with more items to create a tuple and it worked. Example:

mylearning = "Ajit Kumar","April","python",
print(mylearning)
#output: ('Ajit Kumar', 'April', 'python')

print(type(mymistake))
#output:  <class 'tuple'>

Enter fullscreen mode Exit fullscreen mode

It was a lot of learning on weekend. I hope, it will be helpful for you. Put your discussion and suggestion in the comment. I love to hear about Python shortcuts and out-of-box features.

string Article's
30 articles in total
Favicon
Leetcode β€” 2942. Find Words Containing Character
Favicon
Python day-28 Dictionary, Frequency of character using nested loops
Favicon
Python Day-19 csv file,String methods,ASCII,Task
Favicon
Redis Cache - A String story
Favicon
Python Day-22 String Functions logic using loops, Recursion, Tasks
Favicon
Greatest Common Divisor of Strings in Javascript
Favicon
Day 22- String Functions and Recursion
Favicon
Day 21- String Functions
Favicon
Python Day-21 String functions logic using loops
Favicon
Python Day-20 String functions logic using loops,Task
Favicon
Day 20 - String functions
Favicon
Day 19 - CSV file, ASCII, String methods
Favicon
Python Day 6- String Functions,Looping-For,ifelse conditions and Task
Favicon
Python Day 5 - String functions
Favicon
Mastering String Operations in JavaScript πŸš€
Favicon
String Data Structures and Algorithms: Essential Interview Questions
Favicon
Find the First Non-Repeated Character in a String
Favicon
Longest substring without repeating characters
Favicon
Create JS function to remove spaces from giving string. ( Using core js and not in-built trim function.)
Favicon
Write a function that removes duplicate characters from a given string. ( Try to write core JS)
Favicon
Knuth Morris Prat algorithm[Pattern Matching]
Favicon
The JS string replace() method
Favicon
Pergunte ao especialista - Strings
Favicon
Strings
Favicon
C# {String Methods}
Favicon
Extending String for Validation in Dart 3
Favicon
String and Trailing comma, get couple and become, Tuple (): A copy & paste mistake to Error and concept
Favicon
Top 10 String Javascript Interview Coding Question
Favicon
Bash string manipulation
Favicon
C++ ηš„ string η‰©δ»Άεˆ°εΊ•δ½”εΉΎε€‹δ½ε…ƒη΅„οΌŸ

Featured ones: