पायथन स्ट्रिंग्स (उदाहरण के साथ)

इस ट्यूटोरियल में आप पायथन में स्ट्रिंग्स बनाना, प्रारूपित करना, संशोधित करना और हटाना सीखेंगे। साथ ही, आपको विभिन्न स्ट्रिंग ऑपरेशन और फ़ंक्शंस से परिचित कराया जाएगा।

वीडियो: पायथन स्ट्रिंग्स

पायथन में स्ट्रिंग क्या है?

एक स्ट्रिंग पात्रों का एक क्रम है।

एक चरित्र केवल एक प्रतीक है। उदाहरण के लिए, अंग्रेजी भाषा में 26 अक्षर हैं।

कंप्यूटर पात्रों के साथ सौदा नहीं करते हैं, वे संख्याओं (बाइनरी) से निपटते हैं। यद्यपि आप अपनी स्क्रीन पर वर्ण देख सकते हैं, आंतरिक रूप से इसे 0 और 1s के संयोजन के रूप में संग्रहीत और हेरफेर किया जाता है।

किसी संख्या में वर्ण के इस रूपांतरण को एन्कोडिंग कहा जाता है, और रिवर्स प्रक्रिया डिकोडिंग है। ASCII और यूनिकोड कुछ लोकप्रिय एनकोडिंग हैं जिनका उपयोग किया जाता है।

पायथन में, एक स्ट्रिंग यूनिकोड वर्णों का एक क्रम है। यूनिकोड को सभी भाषाओं में प्रत्येक वर्ण को शामिल करने और एन्कोडिंग में एकरूपता लाने के लिए पेश किया गया था। आप यूथोड के बारे में पायथन यूनिकोड से जान सकते हैं।

पायथन में एक स्ट्रिंग कैसे बनाएं?

एकल उद्धरण या दोहरे उद्धरण के अंदर वर्णों को सम्मिलित करके स्ट्रिंग्स का निर्माण किया जा सकता है। यहां तक ​​कि ट्रिपल कोट्स का इस्तेमाल पाइथन में किया जा सकता है, लेकिन आमतौर पर इसका इस्तेमाल मल्टीलाइन स्ट्रिंग्स और डोकस्ट्रिंग्स का प्रतिनिधित्व करने के लिए किया जाता है।

 # defining strings in Python # all of the following are equivalent my_string = 'Hello' print(my_string) my_string = "Hello" print(my_string) my_string = '''Hello''' print(my_string) # triple quotes string can extend multiple lines my_string = """Hello, welcome to the world of Python""" print(my_string)

जब आप प्रोग्राम चलाते हैं, तो आउटपुट होगा:

 नमस्ते नमस्ते नमस्ते नमस्ते, पायथन की दुनिया में आपका स्वागत है

एक स्ट्रिंग में वर्णों का उपयोग कैसे करें?

हम इंडेक्सिंग और स्लाइसिंग का उपयोग करके वर्णों की एक श्रृंखला का उपयोग करके अलग-अलग वर्णों तक पहुंच सकते हैं। इंडेक्स 0. से शुरू होता है। इंडेक्स रेंज से बाहर के कैरेक्टर को एक्सेस करने की कोशिश करने से ए बढ़ा होगा IndexError। सूचकांक एक पूर्णांक होना चाहिए। हम फ़्लोट्स या अन्य प्रकारों का उपयोग नहीं कर सकते, यह परिणाम देगा TypeError

पायथन अपने अनुक्रमों के लिए नकारात्मक अनुक्रमण की अनुमति देता है।

इंडेक्स के -1अंतिम आइटम को संदर्भित करता है, -2दूसरे को अंतिम आइटम और इसी तरह। हम कताई ऑपरेटर :(कोलन) का उपयोग करके एक स्ट्रिंग में कई मदों तक पहुंच सकते हैं ।

 #Accessing string characters in Python str = 'programiz' print('str = ', str) #first character print('str(0) = ', str(0)) #last character print('str(-1) = ', str(-1)) #slicing 2nd to 5th character print('str(1:5) = ', str(1:5)) #slicing 6th to 2nd last character print('str(5:-2) = ', str(5:-2))

जब हम उपरोक्त कार्यक्रम चलाते हैं, तो हमें निम्न आउटपुट मिलते हैं:

 str = programiz str (0) = p str (-1) = z str (1: 5) = घूमना str (5: -2) हूँ

यदि हम किसी इंडेक्स को सीमा से बाहर जाने या पूर्णांक के अलावा अन्य संख्याओं का उपयोग करने का प्रयास करते हैं, तो हमें त्रुटियां मिलेंगी।

 # index must be in range >>> my_string(15)… IndexError: string index out of range # index must be an integer >>> my_string(1.5)… TypeError: string indices must be integers

नीचे दिखाए गए तत्वों के बीच अनुक्रमणिका पर विचार करके स्लाइसिंग को सर्वश्रेष्ठ रूप से देखा जा सकता है।

यदि हम एक सीमा तक पहुंचना चाहते हैं, तो हमें सूचकांक की आवश्यकता है जो स्ट्रिंग से भाग को काट देगा।

स्ट्रिंग साइलिंग पाइथन में

स्ट्रिंग को कैसे बदलें या हटाएं?

तार अपरिवर्तनीय हैं। इसका मतलब है कि एक स्ट्रिंग के तत्वों को एक बार बदलने के बाद उन्हें नहीं सौंपा जा सकता है। हम बस एक ही नाम के लिए अलग-अलग तारों को फिर से असाइन कर सकते हैं।

 >>> my_string = 'programiz' >>> my_string(5) = 'a'… TypeError: 'str' object does not support item assignment >>> my_string = 'Python' >>> my_string 'Python'

हम एक स्ट्रिंग से वर्णों को हटा या हटा नहीं सकते। लेकिन delकीवर्ड का उपयोग करके स्ट्रिंग को पूरी तरह से हटाना संभव है ।

 >>> del my_string(1)… TypeError: 'str' object doesn't support item deletion >>> del my_string >>> my_string… NameError: name 'my_string' is not defined

पायथन स्ट्रिंग ऑपरेशन

ऐसे कई ऑपरेशन हैं जो स्ट्रिंग्स के साथ किए जा सकते हैं जो इसे पायथन में सबसे अधिक उपयोग किए जाने वाले डेटा प्रकारों में से एक बनाता है।

पायथन यात्रा में उपलब्ध डेटा प्रकारों के बारे में अधिक जानने के लिए: पायथन डेटा प्रकार

दो या दो से अधिक स्ट्रिंग्स का संयोजन

Joining of two or more strings into a single one is called concatenation.

The + operator does this in Python. Simply writing two string literals together also concatenates them.

The * operator can be used to repeat the string for a given number of times.

 # Python String Operations str1 = 'Hello' str2 ='World!' # using + print('str1 + str2 = ', str1 + str2) # using * print('str1 * 3 =', str1 * 3)

When we run the above program, we get the following output:

 str1 + str2 = HelloWorld! str1 * 3 = HelloHelloHello

Writing two string literals together also concatenates them like + operator.

If we want to concatenate strings in different lines, we can use parentheses.

 >>> # two string literals together >>> 'Hello ''World!' 'Hello World!' >>> # using parentheses >>> s = ('Hello '… 'World') >>> s 'Hello World'

Iterating Through a string

We can iterate through a string using a for loop. Here is an example to count the number of 'l's in a string.

 # Iterating through a string count = 0 for letter in 'Hello World': if(letter == 'l'): count += 1 print(count,'letters found')

When we run the above program, we get the following output:

 3 letters found

String Membership Test

We can test if a substring exists within a string or not, using the keyword in.

 >>> 'a' in 'program' True >>> 'at' not in 'battle' False

Built-in functions to Work with Python

Various built-in functions that work with sequence work with strings as well.

Some of the commonly used ones are enumerate() and len(). The enumerate() function returns an enumerate object. It contains the index and value of all the items in the string as pairs. This can be useful for iteration.

Similarly, len() returns the length (number of characters) of the string.

 str = 'cold' # enumerate() list_enumerate = list(enumerate(str)) print('list(enumerate(str) = ', list_enumerate) #character count print('len(str) = ', len(str))

When we run the above program, we get the following output:

 list(enumerate(str) = ((0, 'c'), (1, 'o'), (2, 'l'), (3, 'd')) len(str) = 4

Python String Formatting

Escape Sequence

If we want to print a text like He said, "What's there?", we can neither use single quotes nor double quotes. This will result in a SyntaxError as the text itself contains both single and double quotes.

 >>> print("He said, "What's there?"")… SyntaxError: invalid syntax >>> print('He said, "What's there?"')… SyntaxError: invalid syntax

One way to get around this problem is to use triple quotes. Alternatively, we can use escape sequences.

An escape sequence starts with a backslash and is interpreted differently. If we use a single quote to represent a string, all the single quotes inside the string must be escaped. Similar is the case with double quotes. Here is how it can be done to represent the above text.

 # using triple quotes print('''He said, "What's there?"''') # escaping single quotes print('He said, "What\'s there?"') # escaping double quotes print("He said, "What's there? "")

When we run the above program, we get the following output:

 He said, "What's there?" He said, "What's there?" He said, "What's there?"

Here is a list of all the escape sequences supported by Python.

Escape Sequence Description
ewline Backslash and newline ignored
\ Backslash
\' Single quote
" Double quote
a ASCII Bell
 ASCII Backspace
f ASCII Formfeed
ASCII Linefeed
ASCII Carriage Return
ASCII Horizontal Tab
v ASCII Vertical Tab
ooo Character with octal value ooo
xHH Character with hexadecimal value HH

Here are some examples

 >>> print("C:\Python32\Lib") C:Python32Lib >>> print("This is printedin two lines") This is printed in two lines >>> print("This is x48x45x58 representation") This is HEX representation

Raw String to ignore escape sequence

Sometimes we may wish to ignore the escape sequences inside a string. To do this we can place r or R in front of the string. This will imply that it is a raw string and any escape sequence inside it will be ignored.

 >>> print("This is x61 good example") This is a good example >>> print(r"This is x61 good example") This is x61 good example

The format() Method for Formatting Strings

The format() method that is available with the string object is very versatile and powerful in formatting strings. Format strings contain curly braces () as placeholders or replacement fields which get replaced.

We can use positional arguments or keyword arguments to specify the order.

 # Python string format() method # default(implicit) order default_order = "(), () and ()".format('John','Bill','Sean') print('--- Default Order ---') print(default_order) # order using positional argument positional_order = "(1), (0) and (2)".format('John','Bill','Sean') print('--- Positional Order ---') print(positional_order) # order using keyword argument keyword_order = "(s), (b) and (j)".format(j='John',b='Bill',s='Sean') print('--- Keyword Order ---') print(keyword_order)

When we run the above program, we get the following output:

 --- Default Order --- John, Bill and Sean --- Positional Order --- Bill, John and Sean --- Keyword Order --- Sean, Bill and John

The format() method can have optional format specifications. They are separated from the field name using colon. For example, we can left-justify <, right-justify > or center ^ a string in the given space.

हम पूर्णांक को बाइनरी, हेक्साडेसिमल, इत्यादि के रूप में भी प्रारूपित कर सकते हैं और फ्लोट को घातांक प्रारूप में गोल या प्रदर्शित किया जा सकता है। वहाँ आप उपयोग कर सकते हैं स्वरूपण के टन कर रहे हैं। format()विधि के साथ उपलब्ध सभी स्ट्रिंग प्रारूपण के लिए यहां जाएं ।

 >>> # formatting integers >>> "Binary representation of (0) is (0:b)".format(12) 'Binary representation of 12 is 1100' >>> # formatting floats >>> "Exponent representation: (0:e)".format(1566.345) 'Exponent representation: 1.566345e+03' >>> # round off >>> "One third is: (0:.3f)".format(1/3) 'One third is: 0.333' >>> # string alignment >>> "|(:10)|".format('butter','bread','ham') '|butter | bread | ham|'

पुरानी शैली प्रारूपण

हम sprintf()C प्रोग्रामिंग लैंग्वेज में इस्तेमाल किए गए पुराने स्टाइल की तरह स्ट्रिंग्स को फॉर्मेट भी कर सकते हैं। %इसे पूरा करने के लिए हम ऑपरेटर का उपयोग करते हैं ।

 >>> x = 12.3456789 >>> print('The value of x is %3.2f' %x) The value of x is 12.35 >>> print('The value of x is %3.4f' %x) The value of x is 12.3457

आम पायथन स्ट्रिंग तरीके

स्ट्रिंग ऑब्जेक्ट के साथ कई विधियाँ उपलब्ध हैं। जिस format()विधि का हमने ऊपर उल्लेख किया है, वह उनमें से एक है। आमतौर पर इस्तेमाल किया तरीकों में से कुछ कर रहे हैं lower(), upper(), join(), split(), find(), replace()आदि यहाँ सब की एक पूरी सूची है निर्मित अजगर में तार के साथ काम करने के लिए तरीके।

 >>> "PrOgRaMiZ".lower() 'programiz' >>> "PrOgRaMiZ".upper() 'PROGRAMIZ' >>> "This will split all words into a list".split() ('This', 'will', 'split', 'all', 'words', 'into', 'a', 'list') >>> ' '.join(('This', 'will', 'join', 'all', 'words', 'into', 'a', 'string')) 'This will join all words into a string' >>> 'Happy New Year'.find('ew') 7 >>> 'Happy New Year'.replace('Happy','Brilliant') 'Brilliant New Year'

दिलचस्प लेख...