Manipulation na igiya a ciki Python

Sarrafa kirtani a ciki Python muhimmin bangare ne na shirye-shirye, saboda igiyoyi suna ɗaya daga cikin nau'ikan bayanai da aka saba amfani da su a aikace-aikace da yawa. Anan akwai wasu hanyoyi don sarrafa kirtani a cikin Python:

 

Bayyana Zaɓuɓɓuka

Don ayyana kirtani a cikin Python, zaku iya amfani da ko dai guda ɗaya ko ƙididdiga biyu. Duka guda ɗaya da ƙididdiga biyu ana ɗaukar inganci don ƙirƙirar kirtani.

Misali:

str1 = 'Hello, World!'  
str2 = "Python Programming"

 

Samun damar Haruffa a cikin Kirtani

Kuna iya samun dama ga takamaiman hali a cikin kirtani ta amfani da fihirisar sa. Fihirisar tana farawa daga 0 kuma tana ƙirga daga hagu zuwa dama.

Misali:

str = "Hello, World!"  
print(str[0])    # Output: H  
print(str[7])    # Output: W  

 

Yankan igiya

Yanke kirtani yana ba ka damar dawo da wani yanki na kirtani ta amfani da syntax [start:end]. Halin da ke matsayi start yana cikin sakamakon, amma hali a matsayi end ba.

Misali:

str = "Hello, World!"  
print(str[0:5])   # Output: Hello  

 

Tsawon igiya

Don nemo tsawon kirtani, zaku iya amfani da len() aikin.

Misali:

str = "Hello, World!"  
print(len(str))   # Output: 13  

 

Ƙirar Ƙarfafawa

Kuna iya haɗa igiyoyi biyu ko fiye tare ta amfani da + afareta.

Misali:

str1 = "Hello"  
str2 = " World!"  
result = str1 + str2  
print(result)   # Output: Hello World!  

 

Ƙirƙirar Tsara

Don tsara kirtani tare da ƙimar maye gurbin, zaku iya amfani da format() hanyar ko kirtani f( Python 3.6 da sama).

Misali:

name = "Alice"  
age = 30  
message = "My name is {}. I am {} years old.".format(name, age)  
print(message)   # Output: My name is Alice. I am 30 years old.  
  
# Chuỗi f-string  
message = f"My name is {name}. I am {age} years old."  
print(message)   # Output: My name is Alice. I am 30 years old.  

 

Hanyoyin igiyoyi

Python yana ba da hanyoyi masu amfani da yawa don sarrafa kirtani, kamar split(), strip(), lower(), upper(), replace(), join(), da ƙari.

Misali:

str = "Hello, World!"  
print(str.split(","))   # Output: ['Hello', ' World!']  
print(str.strip())   # Output: "Hello, World!"  
print(str.lower())   # Output: "hello, world!"  
print(str.upper())   # Output: "HELLO, WORLD!"  
print(str.replace("Hello", "Hi"))   # Output: "Hi, World!"  

 

Sarrafa kirtani yana Python ba ku damar yin hadaddun ayyuka masu inganci akan bayanan rubutu.