Python

Working with Python Strings – Operations,Functions,Formatting

While working on a real-time project you often need to play around with Strings in your logic, so it’s better to know all the functions and operations you can do with Strings.

Python string can be created using Single or Double quotes. Check out this tutorial on the variables for more info.

ex: temp_var = “MyString”

String Concatenation-

Strings can be concatenated using “+” operator same like Scala.

first_name = "Mahendra"
last_name = "Dhoni"
print(first_name + last_name)
Output: Mahendra Dhoni

Note – As already discussed in this tutorial, String has to be typecasted when concatenated with other types.
ex- print(24 + “tutorials”)
Above example throws exception, like

TypeError: cannot concatenate 'str' and 'int' objects

To resolve this type issue, you need to typecast 24 to string as shown below –
ex – print(str(24)+”tutorials”)

String Replication-

String can be replicated using “*” operator.

print('$' * 5)
print(4*"#")
Output: $$$$$
####

String Slicing-

Strings are stored in a series of individual Characters in Python. Its Index starts with ‘0’. We can access the string in both forward and backward direction. Forward direction index starts with ‘0’ and backward index starts with ‘-1’.

Forward Index:    0     1    2   3
String                      M    a    h    i
BackwardIndex: -4  -3  -2  -1

Slice syntax-
<string> [StartIndex:EndIndex]
<string> [:EndIndex]
<string> [StartIndex:]

Note- StartIndex is Inclusive but EndIndex is exclusive which means if you give startIndex as 1, it considers from index 1 and if you give endIndex as 5, it will not include index 5  value.

Example-

name = "24tutorials"
print name[2:5]
print name[:2]
print name[2:]
Output-
tut
24
tutorials

String Formatting-

Python uses  “%” operator to format a set of variables enclosed in a “tuple” (a fixed size list), together with a format string, which contains normal text together with “argument specifiers”, special symbols like “%s” and “%d”.

name = "MSD"
sr = 51
print("%s strike rate is %d." % (name, sr))
Output: MSD strike rate is 51.

String Inbuilt Functions-

Python provides many in-built functions to make developer’s life easy.

capitalize() It capitalizes the first character of the String.
count(string,begin,end) It Counts number of times substring occurs in a String between begin and end index.
endswith(suffix ,begin=0,end=n) It returns a Boolean value if the string terminates with given suffix between begin and end.
find(substring ,beginIndex, endIndex) It returns the index value of the string where substring is found between begin index and end index.
index(subsring, beginIndex, endIndex) It throws an exception if string is not found and works same as find() method.
isalnum() It returns True if characters in the string are alphanumeric i.e., alphabets or numbers and there is at least 1 character. Otherwise it returns False.
isalpha() It returns True when all the characters are alphabets and there is at least one character, otherwise False.
isdigit() It returns True if all the characters are digit and there is at least one character, otherwise False.
islower() It returns True if the characters of a string are in lower case, otherwise False.
isupper() It returns False if characters of a string are in Upper case, otherwise False.
isspace() It returns True if the characters of a string are whitespace, otherwise false.
len(string) It returns the length of a string.
lower() It converts all the characters of a string to Lower case.
upper() It converts all the characters of a string to Upper Case.
startswith(str ,begin=0,end=n) It returns a Boolean value if the string starts with given str between begin and end.
swapcase() It inverts case of all characters in a string.
lstrip() It removes all leading whitespace of a string and can also be used to remove particular character from leading.
rstrip() It removes all trailing whitespace of a string and can also be used to remove particular character from trailing.

Share This Post

Avatar
An Ambivert, music lover, enthusiast, artist, designer, coder, gamer, content writer. He is Professional Software Developer with hands-on experience in Spark, Kafka, Scala, Python, Hadoop, Hive, Sqoop, Pig, php, html,css. Know more about him at www.saikumar.me

Lost Password

Register