Python String

by Atakan

Hi
In this topic, we will talk about python String properties.
Variable value can be written in single quotes or double quotes.

test_str = "adsa" 	#adsa
test_str2 = 'adasd'	#adasd

print(test_str)
print(test_str2)

Number of characters can be viewed with len

print(len(test_str))	#4

If we want to write the long sentences in the bottom line and show them in one line in the output, we can use the “\” character at end of line.

long_text = "djksahjdsahkjdkahsjhjkdsahkjdsakjh" \
            "lfksdfjdslkfdjls" \
            "gfdgfdg"
print(long_text)	#djksahjdsahkjdkahsjhjkdsahkjdsakjhlfksdfjdslkfdjlsgfdgfdg

If we want to see long sentences as they are

long_text2 = """djksahjdsahkjdkahsjhjkdsahkjdsakjh 
                    lfksdfjdslkfdjls 
                        gfdgfdg"""

print(long_text2)
# djksahjdsahkjdkahsjhjkdsahkjdsakjh 
#                     lfksdfjdslkfdjls 
#                         gfdgfdg

What can we do to show the letters according to the index of the string?

test_str = "alaska"
print(test_str[0] + test_str[1] + test_str[2] + test_str[3] + test_str[4] + test_str[5])  #alaska

to print starting from the end. the last letter is considered -1. Accordingly, we can proceed by shrinking the numbers negatively.

print(test_str[-1] + test_str[-2] + test_str[-3] + test_str[-4] + test_str[-5] + test_str[-6])    #aksala

What can we do to get a range of characters in the string?

test_str = "langpy.com"

print(test_str[0:4])	#lang

To get next from certain index number in string?

test_str = "langpy.com"

print(test_str[0:])  #langpy.com
print(test_str[6:])  #.com

What can we do to find the letter or word index to search for?

test_str = "langpy.com"

print(test_str.find("lan"))  #0
print(test_str.find("an"))  #1
print(test_str.find("g"))  #3
print(test_str.find("gdsa"))  #-1

What can we do to see how many times a letter or word has passed?

test_str = "www.langpy.com"

print(test_str.count("w"))  #3
print(test_str.count("."))  #2
print(test_str.count("a"))  #1
print(test_str.count("x"))  #0

to replace the letter or words we are looking for with something else?

test_str = "langpy"

test_str = test_str.replace("langpy","www.langpy.com")

print(test_str)  #www.langpy.com

Let’s combine parameter and string variables in a string array?

my_first_param = "Hello"
my_second_param = "World"

final_var = '{} {} '.format(my_first_param,my_second_param)	#Could be more than 2
print(final_var)	#Hello World 

You may also like

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. OK Read More