Sunday, October 27, 2019

Python : Strings data structure


Python does not support a character type, these are treated as strings of length one, also considered as substring.

var1 = "Guru99!"
var2 = "Software Testing"
print ("var1[0]:",var1[0])
print ("var2[1:5]:",var2[1:5])

Now there are various string operators

[] => Slice- it gives the letter from the given index. a[1] will give "u" from the word Guru as such ( 0=G, 1=u, 2=r and 3=u)

[ : ] => Range slice-it gives the characters from the given range. x [1:3] it will give "ur" from the word Guru. Remember it will not consider 0 which is G, it will consider word after that is ur.

in => Membership-returns true if a letter exist in the given string

x="Guru"
print "u" in x

u is present in word Guru and hence it will give 1 (True)

not in => Membership-returns true if a letter exist is not in the given string

x="Guru"
print "l" not in x

l not present in word Guru and hence it will give 1

r/R => Raw string suppresses actual meaning of escape characters. Print r'\n' prints \n and print R'/n' prints \n

% - Used for string format %r - It insert the canonical string representation of the object (i.e., repr(o)) %s- It insert the presentation string representation of the object (i.e., str(o)) %d- it will format a number for display

+ It concatenates 2 strings

x="Guru"
y="99"
print x+y

* => Repeat

x="Guru"
y="99"
print x*2


Replace method

oldstring = 'I like Guru99'
newstring = oldstring.replace('like', 'love')
print(newstring)

Change upper and lower case string

string="python at guru99"
print(string.upper())

Capitalize the string also can be done below

string="python at guru99"
print(string.capitalize())

Lower casing can be done like below

string="PYTHON AT GURU99"
print(string.lower())

Concatenating by Joining
print(":".join("Python"))

Reverse a string is also a functon!

string="12345"
print(''.join(reversed(string)))

Splitting the string

word="guru99 career guru99"
print(word.split(' '))

word="guru99 career guru99"
print(word.split('r'))


Strings are immutable !!

x = "Guru99"
x.replace("Guru99","Python")
print(x)


References:
https://www.guru99.com/learning-python-strings-replace-join-split-reverse.html

No comments:

Post a Comment