Python元组练习

Here, we are covering following Python tuple exercises,

在这里,我们将介绍以下Python元组练习

  1. Creating & printing a tuple

    创建和打印元组

  2. Unpacking the tuple into strings

    将元组解包成字符串

  3. Create a tuple containing the letters of a string

    创建一个包含字符串字母的元组

  4. Creating a tuple containing all but the first letter of a string

    创建一个元组,其中包含字符串的除首字母外的所有字母

  5. Reversing a tuple

    反转元组

Consider the following program, it contains all above-mentioned exercises.

考虑以下程序,其中包含所有上述练习。

'''
  1) Creating & printing a tuple 
'''
cities = ("New Delhi", "Mumbai", "Indore")
print("cities: ", cities)
print("cities[0]: ", cities[0])
print("cities[1]: ", cities[1])
print("cities[2]: ", cities[2])
print() # prints a newline

'''
  2) Unpacking the tuple into strings
'''
str1, str2, str3 = cities
print("str1: ", str1)
print("str2: ", str2)
print("str3: ", str3)
print() # prints a newline

'''
  3) Create a tuple containing the letters 
  of a string
'''
tpl = tuple("Hello")
print("tpl: ", tpl)
print() # prints a newline

'''
  4) Creating a tuple containing all but the 
  first letter of a string
'''  
# by direct string
tpl1 = tuple("Hello"[1:])
print("tpl1: ", tpl1)

# by string variables
string = "Hello"
tpl2 = tuple(string[1:])
print("tpl2: ", tpl2)
print() # prints a newline

'''
  5) Reversing a tuple
'''
name = ("Shivang", "Radib", "Preeti")
# using slicing technique
rev_name = name[::-1]
print("name: ", name)
print("rev_name: ", rev_name)

Output

输出量

cities:  ('New Delhi', 'Mumbai', 'Indore')
cities[0]:  New Delhi
cities[1]:  Mumbai
cities[2]:  Indore

str1:  New Delhi
str2:  Mumbai
str3:  Indore

tpl:  ('H', 'e', 'l', 'l', 'o')

tpl1:  ('e', 'l', 'l', 'o')
tpl2:  ('e', 'l', 'l', 'o')

name:  ('Shivang', 'Radib', 'Preeti')
rev_name:  ('Preeti', 'Radib', 'Shivang')


翻译自: https://www.includehelp.com/python/python-tuple-exercises.aspx

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值