Python 3 - Fun with Python String

May 14, 2019

This post some useful tips of using strings, and some issues while dealing with strings

Hope, you have seen Python string format

Check if a string starts with some sequence of characters

to_search = 'my_name'
my_var = 'my_name_is_gorav'
if my_var.startswith(to_search):
    print('Found')

Get substring delimited by some character or string

Example, you have a string:

my_var = 'Name:GyanBlog'

You want to have anything after colon

name = my_var.split(':')[1]

Get first letter capital of string

Example: You have some long string like:

name = 'SERVICE_CLOUD_ACCOUNTS'

And, I want something like:

ServiceCloudAccounts

Then, use this code:

new_name = name.title().replace('_', '')

title() method will give you Service_Cloud_Accounts, then we have to remove any other characters we want

Remove any whitespaces around a string, i.e trim

my_str.strip()

Remove multiple spaces with single space

Your string has multiple spaces in between, and you want to convert them into one only.

import re
s = 'hey,    i have  multiple    spaces'
re.sub("\s+", " ", s);

# Output
'hey, i have multiple spaces'

How to add Curly-braces to string in string format

It works perfectly find with following cases

print('{hi}')

print('{hi} %s' %('hi'))

But, not with

website='GyanBlog.com'
print(f'hi { {website} .com}')

You have to use Double Curly-braces

website='GyanBlog.com'
{% raw %}
print(f'hi {{ {website} .com}}')
{% endraw %}

Get whole string except first letter, or get anything after first character

s = 'GyanBlog'
s[1:]
#Output: yanBlog

Get whole string except last letter

s = 'GyanBlog'
s[:-1]

Similar Posts

Latest Posts