Convert tuple

The tuple data structure is used to store a group of data. The elements in this group are separated by a comma. Once created, the values of a tuple cannot change.

An example of a tuple would be:

personInfo = ("Diana", 32, "New York")

Convert list to a tuple

To convert a list to a tuple you can use the tuple() function.

#!/usr/bin/env python
 
listNumbers = [6,3,7,4]
x = tuple(listNumbers)
print(x)

Convert tuple to list

You can convert an existing tuple to a list using the list() function:

#!/usr/bin/env python
 
x = (4,5)       
listNumbers = list(x)  
print(listNumbers)

Convert tuple to string

If your tuple contains only strings (text) you can use:

#!/usr/bin/env python
 
person = ('Diana','Canada','CompSci')
s = ' '.join(person) 
print(s)

Sort a tuple

Tuples are arrays you cannot modify and don’t have any sort function.

But, there is a way. You can however use the sorted() function which returns a list. This list can be converted to a new tuple.

#!/usr/bin/env python
 
person = ('Alison','Victoria','Brenda','Rachel','Trevor')
person = tuple(sorted(person))
print(person)

Keep in mind a tuple cannot be modified, we simple create a new tuple that happens to be sorted.

String isnumeric

Return True if string is numeric.

Syntax

The format is:

str.isnumeric()

Parameters

None

Example

str = u"someone speak python here? sssss"
print( str.isnumeric() )
 
str = u"12345"
print( str.isnumeric() )

Result:

False
True

String isdecimal

Return True if string is decimal.

Syntax

The format is:

str.isdecimal()

Parameters

None

Example

str = u"1.234"
print( str.isdecimal() )
 
str = u"12345"
print( str.isdecimal() )

Result:

False
True

String isdigit

Return True if string consits only of digits.

Syntax

The format is:

str.isdigit()

Parameters

None

Example

str = u"string digit 1234"
print( str.isdigit() )
 
str = u"12345"
print( str.isdigit() )

Result:

False
True

String capitalize

The method capitalize returns a new string with first letter capitalized.

Syntax

The format is:

str.capitalize()

Parameters

None.

Example

str = "the capitalize method returns the string with first letter capitalized."
print( str.capitalize() )

Result:

The capitalize method returns the string with first letter capitalized.

String count

Return the number of substrings in string.

Syntax

The format is:

str.count(sub)

or

str.count(sub,start,end)

Parameters

Sub substring to count

Example

str = "The string count method returns the number of sub string occurences. "
print( str.count("string") )

Result:

2

Posts navigation

1 2