Skip to content

5 Useful String capabilities in Python

5 useful string capabilities in Python focuses on the key functions that will provide most relevant information on string processing during initial stages of Python programming. Python has a set of built-in methods that can be used on strings, and many search results will provide all the basic operations, whereas this post provides all necessary content for Python strings.

1. String declaration in Python

greet = "Hello World"

Here greet is automatically declared as String as it is referring to a string.

2. Concatenate String is one of the useful string capabilities in Python

greet_mrng = "Hello World, " + "this is a good morning"

3. Other basic string functions in Python

Some examples are:

To convert the string into Upper case in Python:

print(greet.upper())

To Replace a word in Python:

print(greet.replace("Hello", "Gday")

(Refer to following link for all other string functions: Python String Methods (w3schools.com)

4. String Format and add placeholders in the text with variables is one of the powerful string capabilities in Python.

To insert a variable in the text “{}” can be used and use the format function.

price = 49

txt = "The price is {} dollars"

print(txt.format(price))

Alternately

price = 49

txt = f"The price is {price} dollars"

print(txt)

5. String Format add more than one values on the string

quantity = 3

itemno = 567

price = 49

myorder = "I want {} pieces of item number {} for {:.2f} dollars."

print(myorder.format(quantity, itemno, price))

Alternately

myorder = f"I want {quantity} pieces of item number {itemno} for {price:.2f} dollars."

print(myorder)

Leave a Reply

Your email address will not be published. Required fields are marked *