0% found this document useful (0 votes)
4 views3 pages

String Operations in Python

The document provides examples of string concatenation, indexing, and slicing in Python. It demonstrates various operations such as combining strings, accessing characters using positive and negative indexing, and extracting substrings through slicing. Additionally, it highlights errors that occur when using unsupported operations on strings.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views3 pages

String Operations in Python

The document provides examples of string concatenation, indexing, and slicing in Python. It demonstrates various operations such as combining strings, accessing characters using positive and negative indexing, and extracting substrings through slicing. Additionally, it highlights errors that occur when using unsupported operations on strings.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

In [4]: #string concatenation

firstname="saran"
lastname="raj"
fullname=firstname+lastname
print(fullname)
fullname=firstname+" "+lastname
print(fullname)
print(firstname,lastname)
fullname=firstname-lastname

saranraj
saran raj
saran raj
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
Cell In[4], line 9
7 print(fullname)
8 print(firstname,lastname)
----> 9 fullname=firstname-lastname

TypeError: unsupported operand type(s) for -: 'str' and 'str'

In [6]: firstname="saran"
lastname="raj"
fullname=firstname*lastname
print(fullname)

---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
Cell In[6], line 3
1 firstname="saran"
2 lastname="raj"
----> 3 fullname=firstname*lastname
4 print(fullname)

TypeError: can't multiply sequence by non-int of type 'str'

In [8]: firstname="saran"
result=firstname*4
print(result)

saransaransaransaran

In [14]: #printing the string statements


a="learning python"
b="gurukula"
print("you are " +a+" in "+b)
print("you are {a} in {b}".format(a=a,b=b))
print("you are {} in {}".format(a,b))

you are learning python in gurukula


you are learning python in gurukula
you are learning python in gurukula
In [16]: #string indexing
a= "hello"
a[0],a[1],a[2],a[3],a[4],

Out[16]: ('h', 'e', 'l', 'l', 'o')

In [17]: #string indexing - negative indexing


a= "hello"
a[-5],a[-1],a[-2],a[-3],a[-4]

Out[17]: ('h', 'o', 'l', 'l', 'e')

In [19]: #string slicing [start:end-1]


a= "hello"
a[0:4]
a[0:5]

Out[19]: 'hello'

In [22]: #string slicing [start:end-1]


a= "hello"
a[1:4]
a[1:5]

Out[22]: 'ello'

In [23]: #string slicing [start:end-1]


a= "hello"
a[:5]

Out[23]: 'hello'

In [24]: #string slicing [start:end-1]


a= "hello"
a[:]

Out[24]: 'hello'

In [25]: #negative slicing [start:end-1]


a= "hello"
a[-5:-1]

Out[25]: 'hell'

In [26]: #negative slicing [start:end-1]


a= "hello"
a[-5:]

Out[26]: 'hello'

In [27]: #negative slicing [start:end-1]


a= "hello"
a[:]
Out[27]: 'hello'

In [28]: # back progpagation is not possible


a[3:0]

Out[28]: ''

In [32]: # step argument [start:end:step]


a="happy learning"
a[0::2]
a[0::3]
a[0::1]
a[0::4]

Out[32]: 'hyan'

Common questions

Powered by AI

String formatting in Python can be done using concatenation with '+', positional format using '{}'.format(args), and named format using '{name}'.format(name=value). For example, concatenating strings directly with '+': 'You are learning python in gurukula' is expressed via 'you are ' + a + ' in ' + b where a = 'learning python' and b = 'gurukula' . Named formatting is demonstrated by 'you are {a} in {b}'.format(a=a, b=b) and gives the same result; likewise, 'you are {} in {}'.format(a, b) provides similar flexibility .

The step argument in string slicing allows skipping characters by specifying intervals. In the syntax 'string[start:end:step]', 'step' determines which characters to include at specified steps. For instance, 'happy learning'[0::2] results in 'hyan', picking every second character, and '[0::4]' results in 'hlen', picking every fourth character . The step argument allows flexible iteration over a string.

Negative index slicing in Python allows accessing parts of a string from the end, useful for flexible navigations. For instance, 'hello'[-5:-1] extracts 'hell', effectively 'hello' with the last character omitted . Such slicing eases tasks like obtaining a string's suffix or reversing strings without knowing the exact length, offering functionality that complements positive slicing for comprehensive string manipulation.

String concatenation in Python can be approached through '+' operators and join methods. Using '+', strings are combined directly, such as 'firstname' + ' ' + 'lastname' . This method is straightforward but can become inefficient with many strings due to repeated memory allocation. The join method is more efficient for multiple strings, as it avoids creating intermediate strings by internally optimizing the operation. However, one must be cautious with '+' to prevent readability issues and performance bottlenecks when concatenating large numbers of strings excessively.

String concatenation in Python can be done using the '+' operator to combine strings, as demonstrated when 'firstname' and 'lastname' are joined to form 'saranraj' and 'saran raj' . However, using operators like '-' and '*' for concatenation will result in TypeError because these operators are not defined for strings. The '-' operator does not exist for string types, and the '*' operator requires an integer on the right to define repetition of the string, demonstrated when attempting multiplication of 'firstname' by 'lastname' .

Python's string operations enable creating custom messages through concatenation and formatting. Using '+', variables such as 'a = "learning python"' and 'b = "gurukula"' can be joined in custom sentences: "You are " + a + " in " + b, producing 'You are learning python in gurukula'. Alternatively, using 'format()' provides easier parameterization: 'you are {a} in {b}'.format(a=a, b=b)' produces the same message, allowing easy changes or reuse . These operations support personalized and dynamic message creation.

Yes, Python allows constructing strings by repeating characters using '*' with an integer. For example, repeating the string 'saran' four times with 'firstname * 4' results in 'saransaransaransaran' . This operation multiplies the content of the string based on the integer, facilitating the creation of repeated sequence patterns easily.

String slicing in Python is used to extract parts of a string. The basic syntax is 'string[start:end]', where 'start' is inclusive and 'end' is exclusive. For example, slicing 'hello' with '[0:4]' results in 'hell', and with '[1:5]' results in 'ello' . Negative indexing allows accessing elements from the end, for instance, 'hello'[-5:-1] yields 'hell'. Additionally, slicing can include a step argument '[start:end:step]', allowing for skipping characters, as shown in slicing 'happy learning' with '[0::2]' to get 'hyan' .

Python raises TypeError when unsupported operators are used with strings. For example, attempting to subtract strings ('firstname' - 'lastname') leads to a TypeError: unsupported operand type(s) for '-' . Similarly, multiplying a string by another string ('firstname' * 'lastname') results in a TypeError, as only multiplication by an integer is allowed to repeat the string . These errors demonstrate Python's strict type-checking to ensure only appropriate operations are executed with data types.

String indexing in Python allows accessing individual characters using an index in square brackets. Positive indexing starts from 0, with 'hello'[0] accessing 'h'. Negative indexing starts from -1, where 'hello'[-1] accesses 'o' . Positive and negative indexing provide flexibility to access characters from either end of the string, with negative indexes useful for reverse traversal.

You might also like